lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dirk Laurie said:

> Mine is more typically a case where the source string is being parsed,
> e.g. I wish to go from
> 
> y = a * ( b + c * ( d - e )) + f
> 
> to
> 
> t1 = d - e
> t2 = b + c * t1
> y = a * t2 + f

Here is a program that I've used to generate linear code for arithmetic
expressions. It is a recent incarnation of the one described in the
first journal paper on Lua <http://www.lua.org/spe.html> some 20 years ago!
Start reading at "Another unusual facility provided by fallbacks is the
reuse of Lua's parser".
--lhf

local MT={}
local V={}
local N=0

local function var(name)
 local t={name=name}
 V[name]=t
 _G[name]=t
 return setmetatable(t,MT)
end

local function S(a)
 if type(a)=="table" then return a.name else return a or 0 end
end

local function arithfb(a,b,op)
 local i=op .. "(" .. S(a) .. "," .. S(b) .. ")"
 if V[i]==nil then N=N+1; V[i]=var("t"..N,N); print(V[i].name ..'='..i) end
 return V[i]
end

local t={"add", "sub", "mul", "div", "unm", "pow"}
for i,v in next,t do
 MT["__"..v]=function (a,b) return arithfb(a,b,v) end
end

local function vars(s)
 for x in string.gmatch(s,"(%w+)") do var(x) end
end

vars"x,y"
return 2/3*x +(x^2-y^2)/(3*(x^2+y^2)), 2/3*y-2*(x*y)/(3*(x^2+y^2))