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