朱莉娅:变量没有定义 [英] Julia: Variable not defined

查看:126
本文介绍了朱莉娅:变量没有定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量作用域行为似乎很奇怪。代码块

  tp = 1 
函数test2()
println(tp)
结束

效果很好,而

  function test()
if tp == 0
tp = tp-1
end
end

会给出例外tp not defined。什么是错的?

解决方案

由于变量被隐式定义为局部或全局的方式,这是非常棘手的, 在一个函数中会影响整个函数的范围。



在第一种情况下, tp 默认为全局变量,并且它可以按照您的预期工作。但是,在第二种情况下,您将 分配给 tp 。这正如手册的变量范围部分所述: p>


赋值 x = y 引入了一个新的局部变量 x 只有当 x 既不是全局声明的,也不是由任何包含范围之前的代码。

因此,通过分配给 tp ,您已经隐式地将其声明为局部变量!它现在将影响您的全球定义...除了您尝试首先访问它。解决方法很简单:如果要分配给它们,显式声明任何变量为全局变量:

  function test()
全球tp
如果tp == 0
tp = tp-1
结束
结束

这里的行为细微差别,但非常一致。我知道,在我终于明白这是如何工作之前,我通过手册的那部分内容读了一些内容。如果你能想出一个更好的方式来形容它,请说点什么!


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?

解决方案

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!

这篇关于朱莉娅:变量没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆