Reputation: 23
Running this code
module mod1
export foo
function foo()
i=0
for ii in 1:10
global i+=ii
end
i
end
end
mod1.foo()
gives UndefVarError: i not defined
.
It seems that the way to do it is by adding a global
before the variable i
:
module mod2
export bar
function bar()
global i=0
for ii in 1:10
global i+=ii
end
i
end
end
mod2.bar()
This gives: 55
Why does the first method not work? As I understand the for
introduces a new scope. Therefore I need the global inside the loop. But why do I also need it outside of the loop?
(I am using julia 1.5.0)
Upvotes: 2
Views: 298
Reputation: 20248
The correct way to write this would be:
module mod1
export foo
function foo()
i=0
for ii in 1:10
i+=ii
end
i
end
end
julia> mod1.foo()
55
There are 3 scopes introduced here (from outermost to innermost):
mod1
foo
for
bodyThe rules for scoping are explained in the manual. In this particular case: when i
is referred to in the for
body, we first look for a variable named i
defined in that same scope. Since none is found, we look for it in the enclosing scope which is the local scope of foo
... and find the variable declared using i=0
.
If no variable named i
had been found in the local foo
scope, we'd have had to look into the enclosing scope, which is a global scope. And in this case, you'd have had to put the global
keyword to explicitly allow it (because it has performance implications).
Upvotes: 2