I am moving from Julia 0.7 to 1.0. It seems that Julia's rule for the scope of variables changed from 0.7 to 1.0. For example, I want to run a simple loop like this:
num = 0
for i = 1:5
if i == 3
num = num + 1
end
end
print(num)
In Julia 0.7 (and in most of other languages), we could expect num = 1
after the loop. However, it will incur UndefVarError: num not defined
in Julia 1.0. I know that by using let
I can do this
let
num = 0
for i = 1:5
if i == 3
num = num + 1
end
end
print(num)
end
It will print out 1. But I do want to get the num = 1
outside the loop and the let
block. Some answers suggest putting all code in a let
block, but it will incur other problems including UndefVarError
while testing line-by-line. Is there any way instead of using let
blocking? Thanks!
This is discussed here.
Add
global
as shown below inside the loop for thenum
variable.Running in the Julia 1.0.0 REPL:
Edit
For anyone coming here new to Julia, the excellent comment made in the answer below by vasja, should be noted:
See that answer for a good example of using a function for the same code without the scoping problem.
Just remember that inside a function you won't use
global
, since the scope rules inside a function are as you would expect:The unexpected behaviour is only in REPL. More on this here