lua-users home
lua-l archive

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


I would be pleased if readers of this list could think of any improvements
to the following memoize function:

  function memoize (f) 
    -- f must take at most one argument and return at most one result
      local cache = setmetatable({ }, { __mode = 'k' })
      local function update(x, v, ...) -- f(x) returns v, ... 
        assert(select('#', ...) == 0)
        cache[x] = v
        return v
      end

      return function (x, ...)
               assert(select('#', ...) == 0) -- cache works with at most one arg
               local v = cache[x]
               if v ~= nil then
                 return v
               else
                 return update(x, f(x))
               end
             end
  end

I'm especially concerned whether I have the cache's __mode metamethod
set correctly, as I always get confused about the semantics of weak
keys and weak values.


Norman