lua-users home
lua-l archive

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


That's an interesting idea Tom, thanks! Indeed I don't have control of the function definition so it's not easy to use a dummy assignment to create a closure.

2014-09-16 11:26 GMT+02:00 Tom N Harris <telliamed@whoopdedo.org>:
On Tuesday, September 16, 2014 06:36:29 PM Choonster TheMage wrote:
>
> Try this, it seems to work for me.
>
> 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() local _ = i end -- The dummy assignment should
> give each closure a unique upvalue i (suggested by LHF earlier in the
> thread)
>     f.att = i
>     table.insert(funcs, f)
> end
>
> print(funcs[1].att) -- I'd expect 0
> print(funcs[2].att) -- I'd expect 1

local funcs = {}
for i=0,5 do
    local f = load"" -- Basically `function() end'
    f.att = i
    table.insert(funcs, f)
end

Or, if you're not in control of the function definition, then wrap it in a
closure.

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

--
tom <telliamed@whoopdedo.org>