i’ve absolutely seen things like this in the past, but i just tested a simple example (lua 5.3.4) and it worked fine? perhaps there’s some finer point that makes it not work? the reason i was even testing was to suggest an alternative fix – you can just copy i into a local variable inside the for loop to allow closing over it.
anyway, my test case that seems to work fine:
t={ {}, {} }
for i=1,2 do
t[i].action = function() print(i) end
end
t[1].action() --> 1
t[1].action() --> 1
t[2].action() --> 2
what i was going to suggest for your example is:
for i=1,16 do
local i = i -- makes a copy of the loop variable which can be closed over
things[i].action = function()
do_things_with(i) -- uses the local copy of i
end
end
but it seems in this simple example it actually isn’t necessary. i guess i’m writing to see if we can figure out the precise situation where this happens (because it absolutely does… sometimes).
5 Likes