4 ms·
Lua's ability to bind a closure to a mutable variable is a very powerful ability that I use all the time. But due to the way loop variables are handled, the exa
by SomeCallMeTim 15y ago
Lua's ability to bind a closure to a mutable variable is a very powerful ability that I use all the time. But due to the way loop variables are handled, the example that's "broken" in Python works "as expected" in Lua:
fns = {}
for i=1,10 do
fns[i]= function() return i; end
end
for i=1,10 do
print("fns[i]",fns[i]())
end
This produces:
fns[i] 1
fns[i] 2
fns[i] 3
fns[i] 4
fns[i] 5
fns[i] 6
fns[i] 7
fns[i] 8
fns[i] 9
fns[i] 10
If you change the set-up loop to look like this, though:
local j
for i=1,10 do
j=i
fns[i]= function() return i,j; end
end
...then it prints:
fns[i] 1 10
fns[i] 2 10
fns[i] 3 10
fns[i] 4 10
fns[i] 5 10
fns[i] 6 10
fns[i] 7 10
fns[i] 8 10
fns[i] 9 10
fns[i] 10 10
In that case, it has bound the mutable "j" to each of the 10 closures, though you can see it's created a new binding for i on each pass through the loop. It WILL create a new instance of the mutable "j" each time "local j" is executed, though, so if the above code is in a function or another block that's executed more than once, then each time those functions will be bound to a new "j".
EDIT: Get the code markup right.