2

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.

Maths89
  • 476
  • 3
  • 15
  • It sounds like you're doing it the right way. If you include the code you're currently using to do this, we might be able to say how you could improve it. – luther Apr 23 '20 at 04:02
  • Why do you want to do this? – lhf Apr 23 '20 at 16:45

1 Answers1

2

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.

lhf
  • 70,581
  • 9
  • 108
  • 149