Julia: Variable not defined

2019-03-25 19:44发布

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?

1条回答
你好瞎i
2楼-- · 2019-03-25 20:19

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!

查看更多
登录 后发表回答