Utoljára aktív 1749311914

Revízió b5a2df6abcaac8942f5931124618a5e29d5b2a43

rpn.lua Eredeti Playground
1local function rpn_caculator()
2 local char = io.read(1)
3 local acc, op = nil, {}
4 local data_stack = {}
5 while char do
6 if char:match("%s") then
7 if #op ~= 0 then
8 local op_to_eval = table.concat(op)
9 op = {}
10 if op_to_eval == "+" then
11 local y, x = data_stack[#data_stack], data_stack[#data_stack - 1]
12 table.remove(data_stack) table.remove(data_stack)
13 table.insert(data_stack, x + y)
14 elseif op_to_eval == "*" then
15 local y, x = data_stack[#data_stack], data_stack[#data_stack - 1]
16 table.remove(data_stack) table.remove(data_stack)
17 table.insert(data_stack, x * y)
18 elseif op_to_eval == "/" then
19 local y, x = data_stack[#data_stack], data_stack[#data_stack - 1]
20 table.remove(data_stack) table.remove(data_stack)
21 table.insert(data_stack, x / y)
22 elseif op_to_eval == "-" then
23 local y, x = data_stack[#data_stack], data_stack[#data_stack - 1]
24 table.remove(data_stack) table.remove(data_stack)
25 table.insert(data_stack, x - y)
26 elseif op_to_eval == "isqrt" then
27 local x = data_stack[#data_stack]
28 table.remove(data_stack)
29 table.insert(data_stack, x)
30 elseif op_to_eval == "dup" then
31 local x = data_stack[#data_stack]
32 table.remove(data_stack)
33 table.insert(data_stack, x)
34 table.insert(data_stack, x)
35 elseif op_to_eval == "swap" then
36 local y, x = data_stack[#data_stack], data_stack[#data_stack - 1]
37 table.remove(data_stack) table.remove(data_stack)
38 table.insert(data_stack, y)
39 table.insert(data_stack, x)
40 end
41 elseif acc then
42 table.insert(data_stack, acc)
43 acc = nil
44 end
45 io.write("> ")
46 for _, data in ipairs(data_stack) do
47 io.write(data) io.write(" ")
48 end
49 io.write("\n")
50 elseif char:match("%d") then
51 acc = acc and (acc * 10 + tonumber(char)) or tonumber(char)
52 else
53 if acc then
54 table.insert(data_stack, acc)
55 acc = nil
56 end
57 table.insert(op, char)
58 end
59
60 char = io.read(1)
61 end
62end
63
64rpn_caculator()