Variable scope in while loops

Hi all,

a bit more of Julia quark I can not fathom:

julia> a = 10
10

julia> a <= 12
true

julia> while a <= 12
       println(a)
       a += 1
       end
ERROR: UndefVarError: a not defined
Stacktrace:
 [1] top-level scope at ./none:2

This leaves me with two questions:

  1. why isn’t the variable visible in the loop guard?
  2. how can I use a global (or outer scope) variable in a while loop guard?

Thank you.

3 Likes

You need a global a in the while loop.

See also https://github.com/JuliaLang/julia/issues/28789 and Global variables not visible within loops in scripts … this behavior is slated to be changed in interactive contexts. In IJulia/Jupyter it is already changed.

I still have not figured how to code a while loop like this. Here is what I tried:

julia> global a = 10
10

julia> while a <= 12
               println(a)
               a = a + 1
           end
ERROR: UndefVarError: a not defined
Stacktrace:
 [1] top-level scope at ./REPL[3]:2 [inlined]
 [2] top-level scope at ./none:0

julia> while global a <= 12
               println(a)
               global a = a + 1
           end
ERROR: syntax: invalid syntax in "global" declaration

I get similar errors with while loops in a script.

1 Like
julia> global a = 10
10

julia> while a <= 12
           global a
           println(a)
           a = a + 1
       end
10
11
12

julia> global a = 10
10

julia> while a <= 12
           println(a)
           global a = a + 1
       end
10
11
12
5 Likes

That was fast! Thanks.