mcbot/cmds/calc.lua
author Mikael Berthe <mikael@lilotux.net>
Sun, 11 Apr 2010 18:13:18 +0200
changeset 0 89add07d6fe4
child 16 064a50911e05
permissions -rw-r--r--
Initial revision 2010/04/11, mcabber 0.10.1-dev (1892:ea3f9b4f3558)


local function sbox (untrusted_code)
    -- make environment
    local env = {}

    -- run code under environment
    local untrusted_function, message = loadstring(untrusted_code)
    if not untrusted_function then return nil, message end
    setfenv(untrusted_function, env)
    local success, result = pcall(untrusted_function)
    if success then
        return result
    else
        return nil, result
    end
end

-- ---- ----

local function dc (args)
    if not args then return nil, "Give me an expression" end
    -- Downloaded from http://www.math.bas.bg/bantchev/place/rpn/rpn.lua.html
    tb = {}  z = 0
    for tk in string.gmatch(args,'%S+') do
      if string.find(tk,'^[-+*/]$')  then
        if 2>#tb then z = nil break end
        y,x = table.remove(tb),table.remove(tb)
        loadstring('z=x'..tk..'y')()
      else
        z = tonumber(tk)  if z==nil then break end
      end
      table.insert(tb,z)
    end
    n = #tb
    if n==1 and z then return z
    elseif n>1 or z==nil then return nil, "dc: Error!" end
end

local function calc (args)
    if not args then return nil, "Give me an expression" end
    local f, msg = sbox("return "..args)
    if not f then
        return nil, "calc: Cannot evaluate expression"
    end
    return tostring(f)
end

mcbot_register_command("dc", dc)
mcbot_register_command("calc", calc)