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 <> some 20 years ago!
Start reading at "Another unusual facility provided by fallbacks is the
reuse of Lua's parser".

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

local function var(name)
 local t={name=name}
 return setmetatable(t,MT)

local function S(a)
 if type(a)=="table" then return else return a or 0 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]

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

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

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