1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
--[[
Simple calculator to evaluate selected text as a mathematical expression.
Only single-line constant expressions are supported, but you can do
some fairly complex calculations, e.g. sqrt(pi^2*sin(rad(45)))
--]]
-- Copy math functions to global namespace
for k,v in pairs(math) do _G[k] = math[k] end
-- Set window caption for some error messages
geany.banner="Calculator"
-- Grab any selected text
sel=geany.selection()
-- Do we have a selection ?
if (sel==nil) or (#sel==0) then
geany.message("Nothing selected.",
"Select a math expression in the\ncurrent document, and try again.")
return
end
-- Is our selection all on one line ?
if string.find(sel, "\n") then
geany.message("Too many lines!",
"Only single-line expressions are supported.")
return
end
-- Create a function call around the selected expression
func=assert(loadstring("return "..geany.selection()))
-- Did we get our function ?
if not func then
geany.message("Failed to parse expression.")
return
end
-- Call the function
answer=func()
-- Did we get an answer ?
if not answer then
geany.message("Failed to evaluate expression.")
return
end
-- Try to convert answer to a string
answer=tostring(answer)
-- Is the answer now a string?
if not answer then
geany.message("Failed to convert results to text.")
return
end
-- Replace current selection with our answer
geany.selection(answer)
|