by ionfish · 15y ago · 0 comments
[1] http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/
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.
[1] http://brendaneich.com/2010/11/paren-free/ -- see the "Implicit Fresh Bindings" section.
It's also hard for me to see how one could have a 'definitive' semantics without having at least one alternative—not that I claimed that either JS's closure semantics were the only ones going. Presumably the alternative you mean is where the variables present in the local environment are copied on creation of a closure.
I'd also resist the idea that I claimed that JavaScript's closure semantics were in some way definitive, although I can see how one might infer that from what I did write. That being said, given the potential problems with the alternative, I would claim that they're a reasonable choice.
Yes, but what are the issues with fresh let-bindings per iteration?
Presumably the alternative you mean is where the variables present in the local environment are copied on creation of a closure.
No, that's bad -- it leaves you unable to show that objects with mutable state are reducible to closures.