I'm learning Julia as part of my PhD in economics but I've come across an issue that doesn't make sense to me. I'm trying to write a function that performs some preliminary calculations then conducts a while loop and returns some value. I want to do this without using global variables. For some reason I can't get it to work. See the minimal working example below which returns a undefined variable error for z
.
function test_me(n)
x = 2 + 1
y = x - 1
i = y
while i <= n
println(i)
i += 1
z = 3*i
end
return z
end
I can solve the problem easily by making z
a global variable.
function test_me2(n)
x = 2 + 1
y = x - 1
i = y
while i <= n
println(i)
i += 1
global z = 3*i
end
return z
end
I'm confused as I was under the impression that by wrapping the while loop in a function implies that z
is in the local scope and the global declaration is unnecessary. For example the code below works as expected.
function test_me3(n)
i = 1
while i <= n
println(i)
i += 1
z = 3*i
end
return z
end
I apologise if this issue is trivial. Any help is really appreciated. Thanks.
Just put a local z
or alternatively a z = 0
before your while loop such that z
is defined in the loop.
For more on this check out the scoping page of the Julia documentation and the local
keyword docstring.
See also this question/answer: In Julia, is there a way to pass a variable from a local scope to the enclosing local scope?