lua-users home
lua-l archive

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


I tried this snippet Dirk, but unfortunately it has the same pitfall.

2014-09-16 8:01 GMT+02:00 Dirk Laurie <dirk.laurie@gmail.com>:
2014-09-16 0:16 GMT+02:00 Paul Bernier <bernier.pja@gmail.com>:
> Thank you all, I was suspecting it was an optimization. Unfortunately I'd
> have preferred the behavior of LuaJIT or Lua5.1, but it's also because I'm
> in a deviant case (use of debug.setmetatable). Here is a simplified version
> of what I'm doing, just to give you the true motivation of my question:
>
> local proxy = {}
>
> local mt = {
>     __index = function(self, key)
>         return proxy[self][key]
>     end,
>     __newindex = function(self, key, value)
>         if not proxy[self] then
>             proxy[self] = {}
>         end
>         proxy[self][key] = value
>     end,
> }
>
> debug.setmetatable(function()end, mt)
>
> local funcs = {}
> for i=0,5 do
>     local f = function() end
>     f.att = i
>     table.insert(funcs, f)
> end
>
> print(funcs[1].att) -- I'd expect 0
> print(funcs[2].att) -- I'd expec 1

If you really must use a metatable for functions,
you could do this:

local funcs = {}
local factory = function(i)
   local f = function() end
   f.att = i
   return f
   end
end
for i=0,5 do
    table.insert(funcs, factory(i))
end