[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua 5.2 new function reference inside a loop
- From: Tom N Harris <telliamed@...>
- Date: Tue, 16 Sep 2014 05:26:55 -0400
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>