lua-users home
lua-l archive

Re: Another example for syntactically lightweight closures

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


On Feb 7, 2008 4:30 AM, David Manura <dm.lua@math2.org> wrote:
> Approaches for syntactically lightweight closures are also discussed in [1].
>
> [1] http://lua-users.org/wiki/ShortAnonymousFunctions
>
I particularly liked the trick where one makes code strings executable
functions. This combines a few ideas in the discussion, and implements
a simple form of caching.
local llookup = {}
getmetatable('').__call = function(s,...)
 local args,body = s:match('%s*|(.-)|%s*(.+)')
 if not args then
 args = ''
 body = s
 end
 s = 'function('..args..') return '..body..' end'
 local fun = llookup[s]
 if not fun then
 print 'compiling'
 local code = "return " .. s
 fun = assert(loadstring(code))()
 llookup[s] = fun
 end
 return fun(...)
end
print(("|x,y| x+y")(2,3))
print( ("|x,y| x+y")(20,30))
function for_n(n,fun,...)
 for i = 1,n do fun(...) end
end
for_n(3,"print(42)")
output:
compiling
5
50
compiling
42
42
42
steve d.

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