Last active
November 22, 2017 01:18
-
-
Save cipharius/f1f36f8401b82fdbdb829ee46ca9e536 to your computer and use it in GitHub Desktop.
Polish notation parser in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Operations definitions | |
local operations = { | |
["+"] = { | |
Arguments = 2, | |
Operation = function(a, b) return a + b end | |
}, | |
["-"] = { | |
Arguments = 2, | |
Operation = function(a, b) return a - b end | |
}, | |
["*"] = { | |
Arguments = 2, | |
Operation = function(a, b) return a * b end | |
}, | |
["/"] = { | |
Arguments = 2, | |
Operation = function(a, b) return a / b end | |
}, | |
["^"] = { | |
Arguments = 2, | |
Operation = function(a, b) return a ^ b end | |
}, | |
["%"] = { | |
Arguments = 2, | |
Operation = function(a, b) return a % b end | |
}, | |
["<<"] = { | |
Arguments = 2, | |
Operation = function(a, b) return a * 2^b end | |
}, | |
[">>"] = { | |
Arguments = 2, | |
Operation = function(a, b) return math.floor(a / 2^b) end | |
} | |
} | |
function evaluatePN(str) | |
local symbols = {} | |
for symbol in str:gmatch("%S+") do | |
table.insert(symbols, symbol) | |
end | |
while #symbols > 1 do | |
for i=#symbols,1,-1 do | |
local symbol = symbols[i] | |
if operations[symbol] then | |
local op = operations[symbol] | |
local args = {} | |
for j=i+1, i+op.Arguments do | |
local arg = symbols[j] | |
table.insert(args, tonumber(arg)) | |
end | |
assert(#args == op.Arguments, ("Operations requires %d arguments, got %d"):format(op.Arguments, #args)) | |
symbols[i] = op.Operation(unpack(args)) | |
-- Shift symbols array left by argument count | |
for j=i+1,#symbols do | |
symbols[j] = symbols[j+op.Arguments] | |
end | |
end | |
end | |
end | |
return symbols[1] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment