Introduction#
We will use Lua to implement a simple terminal calculator for Polish 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[]
, which we can directly access.
lua compute.lua + 1 2
In the above console, we entered three inputs: "+", "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
:
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 Polish expressions:
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]
-- Convert types
Shell_a = tonumber(arg[2])
Shell_b = tonumber(arg[3])
Finally, output the result:
print(Calculate(Shell_symbol, Shell_a, Shell_b))
Full 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))