function memoize(fn) local t = {} return function(x) local y = t[x] if y == nil then y = fn(x); t[x] = y end return y end end -- And here a very slow function: function fib (n) if n == 1 or n == 2 then return 1 else return fib(n-1) + fib(n-2) end end -- Take the time: function take_time(s) t1 = os.clock(); f = loadstring(s); f(); t2 = os.clock(); print("Time = " .. t2 - t1 .. " secs"); end -- How to use it: take_time("fib(31)") take_time("fib(32)") mf = memoize(fib) take_time("mf(31)") take_time("mf(31)")