lua-users home
lua-l archive

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


This is my first stab at lua programming. And I have not studied the
available documantation all that much. I wonder if there is an elegant
way of of memoizing functions. My first try is this:

fibmemo={}
fibmemo[0] = 1
fibmemo[1] = 1

function fib(n)
   if fibmemo[n]  then return fibmemo[n]
   else
       fibmemo[n]=fib(n-1)+fib(n-2)
       return fibmemo[n]
   end
end

function fibn(n)
   if n < 2 then return 1
   else return fibn(n-1)+fibn(n-2) end
end

What I'm wondering is if there is a way of making a general memoization
pool. Someting in the tune of indexing the pool by function name and
value/values. I would be pleased if there was an easy way of
accomplishing this in one or a few lines of code per function. A
preprocessor would do it too.

MvH Dan Andersson