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 (see "Using fallbacks")

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("z"..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))