I've recently playing around with string manipulation to try to make a calculator that takes only one string and returns an answer. I know I could simply use loadstring to do this, but I am trying to learn more about string manipulation. This is what I have so far: Is there any way I can make it more efficient?
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"))