Julia:未定义变量 [英] Julia: Variable not defined

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

问题描述

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

tp = 1函数 test2()打印(tp)结尾

工作得很好,而

函数测试()如果 tp==0tp=tp-1结尾结尾

给出异常tp 未定义".怎么了?

解决方案

这很棘手,因为变量被隐式定义为局部或全局的方式,而函数中的定义稍后可以影响它们在整个函数中的作用域.

在第一种情况下,tp 默认是一个全局变量,它可以按预期工作.但是,在第二种情况下,您将 assign 分配给 tp.正如手册的范围变量部分所述:p><块引用>

一个赋值 x = y 引入一个新的局部变量 x 只有当 x 既没有被声明为全局的也没有被任何封闭的引入作用域在当前代码行之前或之后."

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

 函数 test()全局 tp如果 tp==0tp=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!

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

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