邱 璇洛 (ゝ∀・)

邱 璇洛 (ゝ∀・)

你好哇(*゚∀゚*)~这里是邱璇洛的博客,常常用来记录一些技术文章和小日常~(σ゚∀゚)σ
twitter
tg_channel

Create a Lua console program in 5 minutes.

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))
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.