Search code examples
stringlualua-tableevaluate

Extracting variables from expression in Lua


I have expressions in lua which contains standard metatable operations .__add,.__sub,.__mul, (+,-,*) For example a+b*xyz-cdeI am trying to extract all free variables in table. For this expression, the table will contain {a,b,xyz,cde}. Right now I am trying it with string operations, like splitting, substituting etc. This seems to work but I feel it as ugly way. It gets little complicated as there may nesting and brackets involved in expressions. For example, the expression (a+b)-c*xyz*(a+(b+c)) should return table {a,b,c,xyz}. Can there be a simple way to extract free variables in expressions? I am even looking for simple way with string library.


Solution

  • If you want to do string processing, it's easy:

    local V={}
    local s="((a+b)-c*xyz*(a+(b+c)))"
    for k in s:gmatch("%a+") do
        V[k]=k
    end
    for k in pairs(V) do print(k) end
    

    For fun, you can let Lua do the hard work:

    local V={}
    do
        local _ENV=setmetatable({},{__index=function (t,k) V[k]=k return 0 end})
        local _=((a+b)-c*xyz*(a+(b+c)))
    end
    for k in pairs(V) do print(k) end
    

    This code evaluates the expression in an empty environment where every variable has the value zero, saving the names of the variables in the expression in a table.