Introduction#
We will use Lua to implement a simple terminal calculator for Polish notation expressions.
Getting Started#
In Lua, it is very easy to get input from the console. The input from the console in Lua becomes an array arg[]
, and we can simply take it.
lua compute.lua + 1 2
In the above console, we entered three items: "+", "1", and "2". In Lua, the data passed from the console is always in the form of strings.
We can retrieve them in compute.lua
as follows:
print(arg[1]) -- +
print(arg[2]) -- 1
print(arg[3]) -- 2
The rest is simple, we just need to write a simple function to calculate the Polish notation expression.
function Calculate(symbol, a, b)
-- Error handling
if ((type(symbol) ~= "string" or (type(a) or type(b)) ~= "number")) then
return "Error: Unknown input type"
end
if (symbol == "+") then
return a+b
elseif (symbol == "-") then
return a-b
elseif (symbol == "*") then
return a*b
elseif (symbol == "/") then
return a/b
else
-- Error handling
return "Error: Unknown symbol type"
end
end
Parsing the console command
Shell_symbol = arg[1]
-- Type conversion
Shell_a = tonumber(arg[2])
Shell_b = tonumber(arg[3])
Finally, output the result
print(Calculate(Shell_symbol, Shell_a, Shell_b))
Complete Code#
Shell_symbol = arg[1]
Shell_a = tonumber(arg[2])
Shell_b = tonumber(arg[3])
function Calculate(symbol, a, b)
if ((type(symbol) ~= "string" or (type(a) or type(b)) ~= "number")) then
return "Error: Unknown input type"
end
if (symbol == "+") then
return a+b
elseif (symbol == "-") then
return a-b
elseif (symbol == "*") then
return a*b
elseif (symbol == "/") then
return a/b
else
return "Error: Unknown symbol type"
end
end
print(Calculate(Shell_symbol, Shell_a, Shell_b))