The variable scope behavior seems quite strange. The code block
tp = 1
function test2()
println(tp)
end
works perfectly well while
function test()
if tp==0
tp=tp-1
end
end
gives the exception "tp not defined". What is wrong?
Variables in Julia can be declared by just writing their name. There's no need to define a datatype with it. Initializing variables can be done at the time of declaring variables. This can be done by simply assigning a value to the named variable.
'global' keyword in Julia is used to access a variable that is defined in the global scope. It makes the variable where it is used as its current scope and refers to the global variable of that name.
This is tricky due to the way variables are implicitly defined as local or global, and the fact that definitions later in a function can affect their scoping in the whole function.
In the first case, tp
defaults to being a global variable, and it works as you expected. However, in the second case, you assign to tp
. This, as is noted in the scope of variables section of the manual:
"An assignment
x = y
introduces a new local variablex
only ifx
is neither declared global nor introduced as local by any enclosing scope before or after the current line of code."
So, by assigning to tp
, you've implicitly declared it as a local variable! It will now shadow the definition of your global… except that you try to access it first. The solution is simple: explicitly declare any variables to be global if you want to assign to them:
function test()
global tp
if tp==0
tp=tp-1
end
end
The behavior here is finely nuanced, but it's very consistent. I know it took me a few reads through that part of the manual before I finally understood how this works. If you can think of a better way to describe it, please say something!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With