While loop and UndefVarError

The variable gets undefined in a while loop.

julia> index = length(fruits)
4

julia> while index > 0
           println(fruits[index])
           index -= 1
       end
ERROR: UndefVarError: index not defined
Stacktrace:
 [1] top-level scope at ./REPL[7]:2

julia> index
4

What version of Julia are you using? The short answer is you need to add global index inside the loop, because the scope of the loop is local and does not “see” the global index variable unless you explicitly tell him to do it.

The even shorter answer is that if you download Julia 1.5 or greater you won’t get that error anymore, and your loop will work as you expect. I would recomend that, to avoid confusion.

5 Likes

Also, if your loop is inside a function (and index is defined inside the function) this will not happen in any version of Julia.