Unexpected scope issue

If I try to run the following

a = 1:10
while length(a)>0
  [0 for i in a]
  a = first(a)+1:last(a)
end

I get an UndefVarError: a not defined error.

If I add a global a like so

a = 1:10
while length(a)>0
  global a
  [0 for i in a]
  a = first(a)+1:last(a)
end

everything runs as expected. I get this in for loops as well (the code is nonsense, but a pretty minimal example).

Is this the intended behavior? This is Julia 1.0.5 on Windows.

Yes, it is intended (in global scope).

Inside a function, the behavior is different. E.g., this works:

function foo()

a = 1:10
while length(a)>0
  [0 for i in a]
  a = first(a)+1:last(a)
end

end

See the docs on variable scope

1 Like

Thanks!