我最近正在研究字符串操作,试图制作一个只需要一个字符串并返回答案的计算器。我知道我可以简单地使用 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"))
最佳答案
您可以使用captures在匹配模式中减少对 string.match() 的调用次数。
local x, op, y = string.match(exp, "^(%d) (%D) (%d)$")
这也消除了修剪 op
结果的需要。
不需要为x
和y
调用转换tonumber()
。当与数字运算符一起使用时,这些将自动转换。
关于string - 使用Lua字符串匹配的计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519001/