<p>I'm writing a function to find <a href="http://projecteuler.net/index.php?section=problems&amp;id=12" rel="noreferrer">triangle numbers</a> and the natural way to write it is recursively:</p>

<pre><code>function triangle (x)
   if x == 0 then return 0 end
   return x+triangle(x-1)
end
</code></pre>

<p>But attempting to calculate the first 100,000 triangle numbers fails with a stack overflow after a while.  This is an ideal function to <a href="http://perl.plover.com/Memoize/" rel="noreferrer">memoize</a>, but I want a solution that will memoize any function I pass to it.</p>

```
```
function memoize (f)
   local cache = {}
   return function (x)
             if cache[x] then
                return cache[x]
             else
                local y = f(x)
                cache[x] = y
                return y
             end
          end
end

triangle = memoize(triangle);
```
```
Note that to avoid a stack overflow, triangle would still need to be seeded.