author | Mikael Berthe <mikael@lilotux.net> |
Thu, 15 Apr 2010 18:57:38 +0200 | |
changeset 16 | 064a50911e05 |
parent 0 | 89add07d6fe4 |
permissions | -rw-r--r-- |
16
064a50911e05
Update command infrastructure
Mikael Berthe <mikael@lilotux.net>
parents:
0
diff
changeset
|
1 |
|
064a50911e05
Update command infrastructure
Mikael Berthe <mikael@lilotux.net>
parents:
0
diff
changeset
|
2 |
local dc = { ["desc"] = "RPN calculator" } |
064a50911e05
Update command infrastructure
Mikael Berthe <mikael@lilotux.net>
parents:
0
diff
changeset
|
3 |
local calc = { ["desc"] = "Calculator" } |
0 | 4 |
|
5 |
local function sbox (untrusted_code) |
|
6 |
-- make environment |
|
7 |
local env = {} |
|
8 |
||
9 |
-- run code under environment |
|
10 |
local untrusted_function, message = loadstring(untrusted_code) |
|
11 |
if not untrusted_function then return nil, message end |
|
12 |
setfenv(untrusted_function, env) |
|
13 |
local success, result = pcall(untrusted_function) |
|
14 |
if success then |
|
15 |
return result |
|
16 |
else |
|
17 |
return nil, result |
|
18 |
end |
|
19 |
end |
|
20 |
||
21 |
-- ---- ---- |
|
22 |
||
16
064a50911e05
Update command infrastructure
Mikael Berthe <mikael@lilotux.net>
parents:
0
diff
changeset
|
23 |
function dc.cmd (args) |
0 | 24 |
if not args then return nil, "Give me an expression" end |
25 |
-- Downloaded from http://www.math.bas.bg/bantchev/place/rpn/rpn.lua.html |
|
26 |
tb = {} z = 0 |
|
27 |
for tk in string.gmatch(args,'%S+') do |
|
28 |
if string.find(tk,'^[-+*/]$') then |
|
29 |
if 2>#tb then z = nil break end |
|
30 |
y,x = table.remove(tb),table.remove(tb) |
|
31 |
loadstring('z=x'..tk..'y')() |
|
32 |
else |
|
33 |
z = tonumber(tk) if z==nil then break end |
|
34 |
end |
|
35 |
table.insert(tb,z) |
|
36 |
end |
|
37 |
n = #tb |
|
38 |
if n==1 and z then return z |
|
39 |
elseif n>1 or z==nil then return nil, "dc: Error!" end |
|
40 |
end |
|
41 |
||
16
064a50911e05
Update command infrastructure
Mikael Berthe <mikael@lilotux.net>
parents:
0
diff
changeset
|
42 |
function calc.cmd (args) |
0 | 43 |
if not args then return nil, "Give me an expression" end |
44 |
local f, msg = sbox("return "..args) |
|
45 |
if not f then |
|
46 |
return nil, "calc: Cannot evaluate expression" |
|
47 |
end |
|
48 |
return tostring(f) |
|
49 |
end |
|
50 |
||
51 |
mcbot_register_command("dc", dc) |
|
52 |
mcbot_register_command("calc", calc) |