lua-users home
lua-l archive

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


> Suppose a C + + math library-"MyDream" know themselves how a complex 
> compound expressions such as "A = (B * C + D) * E" is to handle 
> intelligently.
> Could Lua call my mydream library with the AST of "A=(B * C + D) * E" 
> instead of evaluating it itself somehow?

Here is an optimizing arithmetic expression compiler that
emits calls but can be easily changed to build a tree.
It's a reincarnation of the (1995) code in the SPE paper
	http://www.lua.org/spe.html (see "Using fallbacks")
	http://www.lua.org/slides.html#Overloading%20with%20fallbacks
--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("z"..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))