While loop doesn't inherit variable from global scope in 1.0

I copied the below code directly from the docs in Collections and Data Structures: Iteration.

next = iterate(iter)
while next !== nothing
    (i, state) = next
    # body
    next = iterate(iter, state)
end

I defined iter as iter = 1:3

I’ve tried running it in its own file and in the REPL, and in both cases I get the following error:

ERROR: LoadError: UndefVarError: next not defined

I also tried using the global keyword to explicitly define next as a global variable, which didn’t resolve the issue. Is this a bug, or am I missing something?

2 Likes
julia> let
           next = iterate(iter)
           while next !== nothing
               (i, state) = next
               # body
               next = iterate(iter, state)
           end
       end

julia> 

Above works for me.

julia> iter = 1:3
1:3

julia> while next !== nothing
           global next
           (i, state) = next
           # body
           next = iterate(iter, state)
       end

julia> 

Above also works.

This works for me as well. Do you have any idea why it’s the case that you are able to test the value of next before defining it, or why the code from the docs does not work?

Loops introduce a new scope.

Here is more discussion: Scope and global in REPL (julia 0.7)

Thank you. That clears up my confusion.