Julia中的变量范围 [英] Scope of variables in Julia

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

问题描述

当我运行下面的Julia代码时,出现错误:UndefVarError: globalValue not defined.

When I ran the Julia code below, there was an error: UndefVarError: globalValue not defined.

我认为globalValue是一个全局变量,但不是.因此,如果我在for循环中添加命令"global globalValue",则我的代码将起作用.那么,有人可以看看吗,让我知道发生了什么事?预先感谢!

I thought that the globalValue is a global variable, but it is not. Thus, if I add the command "global globalValue" inside the for loop, my code will work. So, could anyone please have a look at it let me know what happened? Thanks in advance!

globalValue = 1.0;
tempValue   = 0.1;
for ii = 1:10
    # global globalValue; if I add this command, my code will work
    tempValue = 5.0; ## I have a function to update "tempValue"
    if globalValue < tempValue
        globalValue = tempValue;
    end
end

推荐答案

您似乎在使用Julia> = 0.7时,范围规则已更改.

It seems you are on Julia >= 0.7, where the scoping rules have changed.

长话短说,在局部范围(例如for循环)中,全局变量仅继承用于读取,而不能继承用于写入.有两种解决方法:

Long story short, in a local scope, such as your for-loop, global variables are only inherited for reading but not for writing. There are two ways around it:

  • 在作业前(您自己想出的内容)前面加一个明确的global
  • 将所有内容包装在诸如let ... end块的全局局部范围"中(globalValue不再是全局变量了)
  • put an explicit global in front of the assignment (what you figured out yourself)
  • wrap everything in a "global local scope" like let ... end block (globalValue isn't really a global variable anymore)

在您的情况下,第二个选项看起来像

In your case, the second option would look like

let
globalValue = 1.0;
tempValue   = 0.1;
for ii = 1:10
    tempValue = 5.0;## I have a function to update "tempValue"
    if globalValue < tempValue
        globalValue = tempValue;
    end
end
end

您可以在此处找到更多信息:

You can find more information here:

  • https://discourse.julialang.org/t/repl-and-for-loops-scope-behavior-change/ (in particular this post by Stefan, who is one of the authors of Julia
  • https://docs.julialang.org/en/stable/manual/variables-and-scoping/#scope-of-variables-1

尽管我自己觉得这很烦人,但是有充分的理由说明为什么进行了更改.另外,应尽量避免更改全局变量.让我在此处引用该手册(请参见上面的链接):

Although I find this a bit annoying myself, there are good reasons for why the change has been made. Also, on should try to avoid changing globals anyway. Let me quote the manual here (see link above):

许多人考虑避免更改全局变量的值 成为编程最佳实践.原因之一是 远程更改其他模块中全局变量的状态 应当谨慎操作,因为它会使程序出现局部行为 很难推理.这就是为什么范围块引入了 局部范围要求global关键字声明修改意图 全局变量.

Avoiding changing the value of global variables is considered by many to be a programming best-practice. One reason for this is that remotely changing the state of global variables in other modules should be done with care as it makes the local behavior of the program hard to reason about. This is why the scope blocks that introduce local scope require the global keyword to declare the intent to modify a global variable.

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

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