Please these four versions:
Version 1:
for i=1:2
if i>=2; println(z); end
z="Hi"
end
No error
Version 2:
for i=1:2
z="Hi"
g()= println(z)
g()
end
No error
Version 3:
for i=1:2
if i>=2; println(z); end
z="Hi"
g()= println(z)
g()
end
ERROR: z not defined
Version 4:
for i=1:2
if i>=2; println(z); end
z="Hi"
g(x)= println(x)
g(z)
end
No error
My guess is: Version 1 treats `z` in the same way as local variable (let's
call it *local way*). Version 2 treats `z` in the same way as global
variable although it's in a local scope (let's call it *global way*).
Version 3 treats it simultaneously in the local/global way, thus introduce
an error. Version 4 is a walk around and also a better programming habit.
If my guess is right, I further conclude that the main dilemma of Julia is
that it depends on the scope (local/global scope) to decide the treatment
of variables (local/global way); however, when scopes are nested, the
problem appears.
On Wednesday, April 29, 2015 at 4:53:12 PM UTC+2, Sisyphuss wrote:
>
> 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
>>>>
>>>