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

查看:29
本文介绍了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天全站免登陆