Search code examples
for-loopscopejuliascoping

Julia 1.0 UndefVarError - Scope of Variable


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!


Solution

  • This is discussed here.

    Add global as shown below inside the loop for the num variable.

    num = 0
    for i = 1:5
        if i == 3
            global num = num + 1
        end
    end
    print(num)
    

    Running in the Julia 1.0.0 REPL:

    julia> num = 0
    0
    julia> for i = 1:5
               if i == 3
                   global num = num + 1
               end
           end
    julia> print(num)
    1
    

    Edit

    For anyone coming here new to Julia, the excellent comment made in the answer below by vasja, should be noted:

    Just remember that inside a function you won't use global, since the scope rules inside a function are as you would expect:

    See that answer for a good example of using a function for the same code without the scoping problem.