nha*_*avt 9 scope for-loop julia
当我在下面运行Julia代码时,出现了错误:UndefVarError: globalValue not defined.
我认为globalValue是一个全局变量,但事实并非如此.因此,如果我在for循环中添加命令"global globalValue",我的代码将起作用.那么,有谁可以看看它让我知道发生了什么?提前致谢!
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
Run Code Online (Sandbox Code Playgroud)
crs*_*nbr 16
看来你在朱莉娅> = 0.7,其中范围规则已经改变.
长话短说,在本地范围内,例如你的for循环,全局变量只是为了阅读而不是为了写作而继承.它有两种方法:
global在作业前面明确说明(你自己想出什么)let ... endblock "这样的"全局本地范围"中(globalValue不再是一个全局变量)在您的情况下,第二个选项看起来像
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
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到更多信息:
虽然我发现自己有点讨厌,但有很好的理由说明为什么要做出改变.此外,应尽量避免改变全局变量.让我在这里引用手册(见上面的链接):
避免改变全局变量的值被许多人认为是编程的最佳实践.其中一个原因是,应该小心地远程更改其他模块中的全局变量状态,因为这会使程序的本地行为难以推理.这就是引入本地范围的范围块需要global关键字来声明修改全局变量的意图的原因.