Reputation: 81
I understand that the for loops are now local in Julia. But there is something I do not understand. Please consider the following two examples.
Example 1
a = 0
for i = 1:3
a += 1
end
Example 2
a = [0]
for i = 1:3
a[1] += 1
end
Example 1 throws an error message, which I understand. But Example 2 works as it is expected. How should I understand this? Arrays are not variables? Can somebody explain this to me?
Upvotes: 8
Views: 342
Reputation: 69879
This question is essentially a duplicate of Julia scoping: why does this function modify a global variable?, where it is discussed in detail that the difference is that a = ...
is an assignment operation (changes binding of a variable a
) and a[1] = ...
is a setindex!
operation (changes value contained in a collection). Also see Creating copies in Julia with = operator.
I am not marking it as a duplicate only because in your case the first example fails in REPL under Julia 1.4.2 but will work under Julia 1.5 once it is released, see https://github.com/JuliaLang/julia/blob/v1.5.0-rc1/NEWS.md:
The interactive REPL now uses "soft scope" for top-level expressions: an assignment inside a scope block such as a for loop automatically assigns to a global variable if one has been defined already. This matches the behavior of Julia versions 0.6 and prior, as well as IJulia. Note that this only affects expressions interactively typed or pasted directly into the default REPL (#28789, #33864).
Upvotes: 4