Julia: Variable not defined

前端 未结 1 539
礼貌的吻别
礼貌的吻别 2021-02-07 16:44

The variable scope behavior seems quite strange. The code block

tp = 1
function test2()
    println(tp)
end

works perfectly well while

1条回答
  •  一生所求
    2021-02-07 17:10

    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!

    0 讨论(0)
提交回复
热议问题