DEV Community

Tony Colston
Tony Colston

Posted on

RPN calculator in lua

Even though I am old and well into my career I still love to learn. A problem that I saw today is a great learning problem.

There is a lot to gather from writing a small RPN calculator. RPN stands for reverse polish notation. See here if you have no clue what that is.
https://en.wikipedia.org/wiki/Reverse_Polish_notation

My code is below. I used lua but the ideas are universal really and can be implemented in any language.

--[[
super simple stack, uses table functions built into lua
see here: https://www.lua.org/pil/19.2.html
]]--
local stack = {}
function stack_push(s,val)
        table.insert(s,val)
end
function stack_pop(s)
        return table.remove(s)
end

--[[
take value/operation from input
use the stack to perform the operation
]]--
function take(input,stack)
        -- get a value from input
        local op_or_value = table.remove(input,1)
        -- check if this is a number or not
        if tonumber(op_or_value) ~= nil then
                print("pushing number: " .. op_or_value)
                stack_push(stack,tonumber(op_or_value))
        elseif op_or_value == "+" then -- handle the plus operation
                local v1 = stack_pop(stack)
                local v2 = stack_pop(stack)
                print("v1 and v2: " .. v1 .. " "  .. v2)
                local res = v1 + v2
                stack_push(stack,res) -- put the value back on the stack
        end
end

local input = { "9", "10", "+" }

take(input,stack)
take(input,stack)
take(input,stack)

for i,v in ipairs(stack) do
        print(v)
end
Enter fullscreen mode Exit fullscreen mode

The way I am solving the problem in the larger picture is I am taking input from an array and using a stack. You read the next item from the input and do something with it.

If the item is a number you need to store it somewhere and I am using a stack for this.
If the item is an operation (plus,minus,times,etc...) then you need to perform that operation. Since all of the operations I mentioned have two arguments, you pull those two values from the stack and perform the operation.

The final step is you push the result back on the stack. You do this step so that the next operation could use the result as a value.

I only implemented the "+" operation but the other operations would be similar.

Keep learning!

Top comments (0)