Skip to content

Instantly share code, notes, and snippets.

@imliam imliam/calculate.lua
Created Mar 29, 2017

Embed
What would you like to do?
Lua - Recursive Calculation
operation = {4, '+', 6, '-', 2}
function calculate(...)
local tbl={...}
if tbl[2] then
if tbl[2]=='+' then
table.insert(tbl, 1, tbl[1] + tbl[3])
table.remove(tbl, 2)
table.remove(tbl, 3)
table.remove(tbl, 4)
return calculate(tbl)
elseif tbl[2] == '-' then
table.insert(tbl, 1, tbl[1] - tbl[3])
table.remove(tbl, 2)
table.remove(tbl, 3)
table.remove(tbl, 4)
return calculate(tbl)
elseif tbl[2] == '*' then
table.insert(tbl, 1, tbl[1] * tbl[3])
table.remove(tbl, 2)
table.remove(tbl, 3)
table.remove(tbl, 4)
return calculate(tbl)
elseif tbl[2] == '/' then
table.insert(tbl, 1, tbl[1] / tbl[3])
table.remove(tbl, 2)
table.remove(tbl, 3)
table.remove(tbl, 4)
return calculate(tbl)
end
return tbl[1]
end
return tbl[1]
end
print(calculate(operation))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.