For loops allocated new variables iff it introduces them, eg
function test1()
l = []
for i in 1:2
push!(l, ()->(j=i; i=i+1; j))
end
l
end
function test2()
l = []
i = 9 # note: only different line
for i in 1:2
push!(l, ()->(j=i; i=i+1; j))
end
l
end
function testl(l)
for i in 1:5
l[1]()
end
l[2]()
end
testl(test1()) # 2
testl(test2()) # 7
While I understand the rule and it is in accordance with the
documentation and thus not a bug, I am curious about the reasons behind
this design. At a first glance, it seems it could be a source of subtle
bugs, so there must be some advantages to balance that.
(I have searched the issues but 'for' is so common that I could not
locate anything useful --- sorry if this was discussed before).
Best,
Tamas