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