Another undefined variable puzzle

Here is some code that (I think) ought to work, but doesn’t:

module foo

x = 1        # line 3
while true
    y = x    # line 5
    x = 4    # line 6
    break
end

end # module

The error message (below) says that x on line 5.is undefined in local scope. This message goes away if I remove line 6. With or without line 6, the assignment on line 3 ought to prevent this problem. What am I missing?

julia> include("foo.jl")
ERROR: LoadError: UndefVarError: `x` not defined in local scope
Suggestion: check for an assignment to a local variable that shadows a global of the same name.
Stacktrace:
 [1] top-level scope
   @ ~/txt/mapmix/julia/MapMix/test/foo.jl:5
 [2] include(fname::String)
   @ Main ./sysimg.jl:38
 [3] top-level scope
   @ REPL[2]:1
in expression starting at /Users/rogers/txt/mapmix/julia/MapMix/test/foo.jl:1

You need to specify explicitly that you want to access the global variable x:

module foo

x = 1        
while true
    global x # newline !!!
    y = x    
    x = 4    
    break
end

end # module

We all agree that is not easy to remember, but there is a good reason for this: to discourage the use of (non-const) global variables, since they are dangerous for the performances and involuntary overwriting. Details here (but this part of the manual is hard to read, IMO): Scope of Variables · The Julia Language

I don’t know what you are trying to do exactly, but a good approach here would be to incorporate the code in a function, since x is no longer a global variable:

module foo

function func()
    x = 1        # line 3
    while true
        y = x    # line 5
        x = 4    # line 6
        break
    end
    return nothing
end

end # module
3 Likes