Undefined variable in loop

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