1 | -- simple PN math evaluator |
2 | -- expects input in "input" |
3 | |
4 | tokens = {} |
5 | for token in string.gmatch(input, "[^%s]+") do |
6 | table.insert(tokens, token) |
7 | end |
8 | |
9 | stack = {} |
10 | |
11 | function push(x) table.insert(stack, x) end |
12 | function pop() local x = stack[#stack]; stack[#stack] = nil; return x end |
13 | |
14 | for i = #tokens, 1, -1 do |
15 | token = tokens[i] |
16 | if token:match('^[0-9]+$') then |
17 | push(tonumber(token)) |
18 | else |
19 | arg1 = pop() |
20 | arg2 = pop() |
21 | if token == '+' then |
22 | push(arg1+arg2) |
23 | elseif token == '*' then |
24 | push(arg1*arg2) |
25 | else |
26 | error("Unknown operation: "..token) |
27 | end |
28 | end |
29 | end |
30 | |
31 | return pop() |
test run test run with input download show line numbers
Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
No comments. add comment
Recognizer | Recognition Result | Visualize | Recalc |
---|---|---|---|
#308 | 639 | [visualize] |
Snippet ID: | #37 |
Snippet name: | PN Math Evaluator |
Eternal ID of this version: | #37/1 |
Text MD5: | 602ffbe90ec65a817ed361a9c1b49507 |
Author: | stefan |
Category: | |
Type: | Lua code |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2013-12-15 09:15:51 |
Source code size: | 639 bytes / 31 lines |
Pitched / IR pitched: | Yes / Yes |
Views / Downloads: | 1529 / 362 |
Referenced in: | [show references] |