lua-users home
lua-l archive

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


Veli-Pekka Tätilä wrote:
> Fabien wrote:
>> > If using alpha compilers gives you the heebie jeebies, you can also do
>> > something like this:
>> >
>> > function L(args)
>> >  return function(exp)
>> >    return assert(loadstring("return function("..args..")"
>> >      .." return "..exp.." end"))()
>> >  end
>> > end
>> You probably want to perform some compilation caching, indexing compiled
>> functions with their source, so that you keep acceptable performances
>> when
>> lambdas occur in loops (i.e. virtually always).
> A good point. That's a form of memoization. Is there a memoize module
> for Lua like the one in Perl? One can easily do it on demand for a
> particular function by hand, of course.
> 
Not built in. I think there's a few on the wiki (look for Memoization or
FuncTables, I believe). Here's the one I use, developed from wiki code
and discussions on IRC (warning: not very heavily tested):

memoize = (function(f) return f(f) end)(function(f)
        local memos = {}
        local function findmemo(memo, args, first, ...)
                local argv = { ... }
                if #argv == 0 then
                        if memo[first] == nil then
                                args[#args+1] = first
                                memo[first] = { f(unpack(args)) }
                        end
                        return unpack(memo[first])
                else
                        args[#args+1] = first
                        memo[first] = memo[first] or {}
                        return findmemo(memo[first], args, ...)
                end
        end
        return function(...)
                local argc = #({...})
                memos[argc] = memos[argc] or {}
                return findmemo(memos[argc], {}, ...)
        end
end)

Use as, for example, 'L = memoize(L)'
	Ben