Here's a variant version of your code:
```
for i=1:10
if i>=2; println(z); end
z=2
g()=(*global z*; 2z)
println(z)
end
```
If `z` is defined global, there will not be any error. I would have like to
use `nonlocal`, but there isn't this keyword in Julia.
In my personal opinion, the magic in your original code is that when the
compiler see the definition of `g()`, it will try to do some *amazing *things
on the compilation of `z`.
On Wednesday, April 29, 2015 at 4:37:24 PM UTC+2, Pooya wrote:
>
> That's exactly my question: Why should defining a function inside the loop
> mess with the variables in the loop?
>
> On Wednesday, April 29, 2015 at 10:33:03 AM UTC-4, Sisyphuss wrote:
>>
>> Another *miracle* here is that if you delete "g()=2z", there will be no
>> error!
>>
>>
>> On Wednesday, April 29, 2015 at 3:53:23 PM UTC+2, Pooya wrote:
>>>
>>> Can someone explain why this is the desired behavior? z is defined until
>>> the end of first iteration in the for loop, but not in the beginning of the
>>> next:
>>>
>>> julia> for i=1:10
>>> if i>=2; println(z); end
>>> z=2
>>> g()=2z
>>> println(z)
>>> end
>>> 2
>>> ERROR: z not defined
>>> in anonymous at no file:2
>>>
>>