lua-users home
lua-l archive

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


> Is generic external memoization of recursive functions at all possible in
> Lua?
> 
> [...]
> 
> local function fibonacci (n) -- this function does not know it is going to
> be memoized.
> 
>     return n < 3 and 1 or fibonacci (n - 2) + fibonacci (n - 1) -- I want
> to make these calls memoized too.
> 
> end
> 
> local fibonacci_memoized = memoize (fibonacci)

The previous line are creating a new local, and with a different
name. To substitute the memorized version for the original one you have
to put it at the same place:

-- use the previously declared 'fibonacci' local variable
fibonacci = memoize (fibonacci)

-- Roberto