Undefined variable in loop

d = 0
while ym <= 1 && d < dotmax
d = d+1
end
This part of my program gives this error. What is the reason?
LoadError: UndefVarError: d not defined

This is a common scoping issue that I encountered. The loop doesn’t have the variable d in its scope, it creates its own local variable d which is then currently undefined. This is a unique aspect of working in the global scope and it’s one of the reasons why it is recommended to try to work in more locally defined scopes such as in functions and in let blocks:

function example_that_works()
    d = 0
    while ym <= 1 && d < dotmax
        d = d+1
    end
end
example_that_works()

# This also works because "let" has its own local scope
let
    d = 0
    while ym <= 1 && d < dotmax
        d = d+1
    end
end

Otherwise, you can fix this by declaring d as global:

global d = 0

but this is not recommended for performance reasons (better to just wrap everything in a main() function):

This behaviour can seem unintuitive, and I don’t fully understand it myself, but it’s been discussed before here.

2 Likes

What version of Julia are you using? In recent versions, this would work in the REPL or give you a specific error in a script indicating that you need to explicitly mark the variable in the loop as global. It’s highly recommended to use the most recent stable release, which would be 1.6 currently.

1 Like

Most recent stable release is 1.7.0, but 1.6 should have the same behavior.

Hah, I forgot that we managed to make that release finally :joy:

4 Likes