lua-users home
lua-l archive

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


Richard Hundt wrote:

   __newindex = function(func, key, val)
      local meta = func_meta[func]
      if meta and meta.__newindex then
         if type(meta.__newindex) == "function" then
            return meta:__newindex(key, val)
         else
            meta.__newindex[key] = val -- HERE
         end
      end
   end;
   -- the rest of the meta table events here...
})

Aplogies, I had some dain brammage in my code in my previous post.

To optimise for lookup, we could "flatten" out the meta events, keeping each in a separate table, so we don't need to test if we have a function "__index" handler or a table:

local func_meta = { }
setmetatable(func_meta, { __mode = "k" })

local func_meta__index = { }
setmetatable(func_meta__index, { __mode = "k" })

local func_meta__newindex = { }
setmetatable(func_meta__newindex, { __mode = "k" })

debug.setmetatable(function() end, {
   __index = function(func, key)
      local meta = func_meta__index[func]
      if meta then
         return meta[key]
      end
   end;
   __newindex = function(func, key, val)
      local meta = func_meta__newindex[func]
      if meta then
         meta[key] = val
      end
   end
})

function setfmeta(func, meta)
   func_meta[func] = meta
   func_meta__index[func] = meta.__index
   func_meta__newindex[func] = meta.__newindex
   return func
end

function getfmeta(func)
   return func_meta[func]
end

Cheers,
Rich