Object not defined in Loop

Viewed 79

I create an object and then try to use it in a loop

a = 0
for i in 1:2
        a += 1
end

However, this results in the following error:

UndefVarError: a not defined

Have I forgotten how loops work or what is going wrong?

1 Answers

The point is that your a is a global variable and in Julia versions between 1.0 and 1.4.2 the local scoping for variables within loops was introduced. More precisely if you do not explicitly say you want to mutate a global variable (global a += 1) a new variable within a local scope is introduced.

The best thing to do is to upgrade to Julia 1.5. Julia 1.5 has introduced back soft scoping in the REPL.

If you need to stick with the current Julia version you could use global keyword or place your code in a function or use Jupyter notebook instead (that has soft scoping) or surround your code around let...end block such as:

 let
    a = 0
    for i in 1:2
        a += 1
    end
    a
end
Related