I still think the solution I proposed would work in this case (which is discussed in the 1.5 blog):
Despite the “on paper” simplicity of the 1.0 scope rule, many people found it unintuitive and annoying. Consider the following example:
s = 0 for i = 1:10 s = s + i end println(s)
One would naively guess that this prints the number
55 , and prior to Julia 1.0 that’s exactly what it did. But in 1.0, we consistently made
for loops introduce new local scopes, which means that this code would throw an undefined variable error because
s is deemed to be local to the loop: since there is no pre-existing local
s (only a global
s ) and
s is assigned in the loop, it is local and the first iteration of the loop tries to access an undefined local
My proposed solution was to check if there was a “read” of a variable before there was a “write” to it in the loop. In this case there is:
s + i “reads” the value of
s. Then, that would mean that the variable must have existed prior to entering this loop, and
s would have become global inside the loop.
So the simple rule “if you assign to a variable in a local scope (function or loop) and there’s no local by that name, then that assignment creates a new local variable” would work just fine in a global scope, if supplemented with “was there a read first?”.