Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Variable not defined

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?

like image 667
warsaga Avatar asked Jul 18 '14 16:07

warsaga


People also ask

How do you declare a variable in Julia?

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.

What is global variable in Julia?

'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.


1 Answers

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 variable x only if x 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!

like image 100
mbauman Avatar answered Sep 21 '22 15:09

mbauman