使用Lua字符串匹配的计算器。

我最近正在玩弄字符串操作,试图制作一个只需要一个字符串并返回答案的计算器。我知道我可以简单地使用loadstring来实现这一点,但我正在尝试更多地了解字符串操作。这是我目前的内容:有没有办法使它更有效率?

function calculate(exp)
    local x, op, y = 
        string.match(exp, "^%d"), 
        string.match(exp, " %D"), 
        string.match(exp, " %d$") 
    x, y = tonumber(x), tonumber(y)
    op = op:sub(string.len(op))
    if (op == "+") then
        return x + y
    elseif (op == "-") then
        return x - y
    elseif (op == "*") then
        return x * y
    elseif (op == "/") then
        return x / y
    else
        return 0
    end
end

print(calculate("5 + 5"))
点赞
用户173806
用户173806

你可以在匹配模式中使用捕获,来减少对string.match()的调用次数。

local x, op, y = string.match(exp, "^(%d) (%D) (%d)$")

这也消除了对op结果进行修剪的需要。

在使用数字运算符时,无需调用tonumber()以将xy进行转换,它们将自动转换。

2014-03-19 23:01:42