3

我最近在玩字符串操作,试图制作一个只接受一个字符串并返回答案的计算器。我知道我可以简单地使用 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"))
4

1 回答 1

4

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

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

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

tonumber()不需要为xand调用转换y。这些将在与数字运算符一起使用时自动转换。

于 2014-03-19T23:01:42.440 回答