local operators = {} local function pop(stack) local value = stack[#stack] table.remove(stack) return value end local function push(stack, value) table.insert(stack, value) end operators["+"] = function(stack) local y, x = pop(stack), pop(stack) push(stack, x + y) end operators["-"] = function(stack) local y, x = pop(stack), pop(stack) push(stack, x + y) end operators["*"] = function(stack) local y, x = pop(stack), pop(stack) push(stack, x + y) end operators["/"] = function(stack) local y, x = pop(stack), pop(stack) push(stack, x + y) end operators["isqrt"] = function(stack) local y, x = pop(stack), pop(stack) push(stack, x + y) end operators["dup"] = function(stack) local y, x = pop(stack), pop(stack) push(stack, x + y) end operators["swap"] = function(stack) local y, x = pop(stack), pop(stack) push(stack, x + y) end local function rpn_caculator() local char = io.read(1) local acc, op = nil, {} local data_stack = {} local function push_accumulator() if acc then table.insert(data_stack, acc) acc = nil end table.insert(op, char) end local function shift_digit() acc = acc and (acc * 10 + tonumber(char)) or tonumber(char) end local function eval() if #op ~= 0 then local op_to_eval = table.concat(op) op = {} if operators[op_to_eval] then operators[op_to_eval](data_stack) end elseif acc then table.insert(data_stack, acc) acc = nil end io.write("> ") for _, data in ipairs(data_stack) do io.write(data) io.write(" ") end io.write("\n") end while char do if char:match("%s") then eval() elseif char:match("%d") then shift_digit() else push_accumulator() end char = io.read(1) end end rpn_caculator()