views:

175

answers:

2

Recently, Lee Baldwin showed how to write a generic, variable argument memoize function. I thought it would be better to return a simpler function where only one parameter is required. Here is my total bogus attempt:

local function memoize(f)
   local cache = {}

   if select('#', ...) == 1 then
      return function (x)
                if cache[x] then
                   return cache[x]
                else
                   local y = f(x)
                   cache[x] = y
                   return y
                end
              end
   else
      return function (...)
                local al = varg_tostring(...)
                if cache[al] then
                   return cache[al]
                else
                   local y = f(...)
                   cache[al] = y
                   return y
                end
             end
   end
end

Obviously, select('#', ...) fails in this context and wouldn't really do what I want anyway. Is there any way to tell inside memoize how many arguments f expects?


"No" is a fine answer if you know for sure. It's not a big deal to use two separate memoize functions.

+2  A: 

I guess you could go into the debug info and determine this from the source-code, but basically it's a "no", sorry.

No problem. I won't waste anymore time searching then. ;-)
Jon Ericson
FYI, you might be able to implement this in C, but it would only be able to examine Lua functions and not C functions.
+2  A: 

I'm pretty sure you can't do that in Lua.

steffenj
Thanks for the confirmation.
Jon Ericson