Skip to content

Instantly share code, notes, and snippets.

@aristidb
Created May 24, 2018 22:20
Show Gist options
  • Save aristidb/ae7cb14c6cccab0edd0f8b05bf7c24da to your computer and use it in GitHub Desktop.
Save aristidb/ae7cb14c6cccab0edd0f8b05bf7c24da to your computer and use it in GitHub Desktop.
function Calculator:expression(expr)
local res
local function match(pattern)
local pos
_, pos, res = expr:find(pattern)
if pos then
expr = expr:sub(pos+1)
end
return pos
end
while true do
print("Expr: <" .. expr .. ">")
print(table.unpack(self.stack))
if match("^%s*(%d+%.?%d*[eE]?%d*)") then
table.insert(self.stack, tonumber(res))
elseif match("^%s*([%+-%*/^%w])") then
if res == "l" then
local x = table.remove(self.stack)
table.insert(self.stack, math.log(x))
elseif res == "e" then
local x = table.remove(self.stack)
table.insert(self.stack, math.exp(x))
else
local b = table.remove(self.stack)
local a = table.remove(self.stack)
if a == nil or b == nil then
return "Not enough arguments"
end
if res == "+" then
table.insert(self.stack, a + b)
elseif res == "-" then
table.insert(self.stack, a - b)
elseif res == "*" then
table.insert(self.stack, a * b)
elseif res == "/" then
table.insert(self.stack, a / b)
elseif res == "^" then
table.insert(self.stack, math.pow(a, b))
elseif res == 's' then
table.insert(self.stack, b)
table.insert(self.stack, a)
elseif res == 'p' then
table.insert(self.stack, string.format('%s %s', a, b))
else
return "Invalid operator: " .. res
end
end
else
break
end
end
if not expr:match("^%s*$") then
return "Unparsed: " .. expr
elseif #self.stack then
return "Result: " .. self.stack[#self.stack]
else
return "No result"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment