lua-users home
lua-l archive

Re: evolutionary programming & Lua

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


Steve Dekorte wrote:
 >> So make a function that turns:
 >> {add,7,{mul,4,3}}
 >> into:
 >> myFunc = dostring("return function () return args.1 + ( args.2 * args.3
)")
 Can I play? Forgive me for intruding into the conversation, but this is
a neat puzzler that I'd love to see the "right" way to solve. I came up
with the following, which is almost certainly NOT the "right" way ;-) but
gets the job done:
function eval(t)
 if type(t)=="table" then
 return "("..t[1](t[2],t[3])..")"
 else
 return argcat(t)
 end
end
function argcat(t)
 local arg = "p"..tostring(t)
 local sep = ((args=="") and "") or ","
 args = args..sep..arg
 return arg
end
function binopcat(x,op,y) return eval(x)..op..eval(y) end
function add(x,y) return binopcat(x,"+",y) end
function sub(x,y) return binopcat(x,"-",y) end
function mul(x,y) return binopcat(x,"*",y) end
function div(x,y) return binopcat(x,"/",y) end
function compile(t)
 args = "" -- global, easier
 local body = eval(t)
 return dostring("return function("..args..") return "..body.." end")
end
-- here 1,2,3 are just place-holders for arguments during compile
F = compile{add,1,{mul,2,3}}
-- now execute with real values
print( F(1,2,3) )
print( F(2,3,4) )
print( F(3,4,5) )
print( F(4,5,6) )
print( F(5,6,7) )
 Has anyone ever written a Lua interpreter with Lua?
 Cheers,
 Dave

AltStyle によって変換されたページ (->オリジナル) /