Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A calculator using Lua string matching

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"))
like image 735
user3314993 Avatar asked Sep 18 '26 20:09

user3314993


1 Answers

You can use captures in the matching pattern to reduce the number of calls to string.match().

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

This also eliminates the need to trim the op result.

The conversion tonumber() does not need to be called for x and y. These will automatically be converted when used with the numeric operators.

like image 114
gwell Avatar answered Sep 20 '26 15:09

gwell