Julia 1.0 UndefVarError-变量范围 [英] Julia 1.0 UndefVarError - Scope of Variable
问题描述
我正在从Julia 0.7移到1.0.似乎Julia的变量范围规则从0.7更改为1.0.例如,我想运行一个简单的循环,如下所示:
I am moving from Julia 0.7 to 1.0. It seems that Julia's rule for the scope of variables changed from 0.7 to 1.0. For example, I want to run a simple loop like this:
num = 0
for i = 1:5
if i == 3
num = num + 1
end
end
print(num)
在Julia 0.7(以及大多数其他语言)中,我们可以期望循环后为num = 1
.但是,它将在Julia 1.0中产生UndefVarError: num not defined
.我知道通过使用let
我可以做到这一点
In Julia 0.7 (and in most of other languages), we could expect num = 1
after the loop. However, it will incur UndefVarError: num not defined
in Julia 1.0. I know that by using let
I can do this
let
num = 0
for i = 1:5
if i == 3
num = num + 1
end
end
print(num)
end
它将打印出1.但是我确实想将num = 1
放在循环和let
块之外.一些答案建议将所有代码放在let
块中,但是在逐行测试时会引起其他问题,包括UndefVarError
.有什么方法可以代替使用let
阻止吗?谢谢!
It will print out 1. But I do want to get the num = 1
outside the loop and the let
block. Some answers suggest putting all code in a let
block, but it will incur other problems including UndefVarError
while testing line-by-line. Is there any way instead of using let
blocking? Thanks!
推荐答案
在此处中对此进行了讨论.
在num
变量的循环内如下所示添加global
.
Add global
as shown below inside the loop for the num
variable.
num = 0
for i = 1:5
if i == 3
global num = num + 1
end
end
print(num)
在Julia 1.0.0 REPL中运行:
Running in the Julia 1.0.0 REPL:
julia> num = 0
0
julia> for i = 1:5
if i == 3
global num = num + 1
end
end
julia> print(num)
1
修改
对于来到Julia的新手,请注意vasja在下面的答案中做出的出色评论:
For anyone coming here new to Julia, the excellent comment made in the answer below by vasja, should be noted:
请记住,在函数内部您不会使用全局函数,因为函数内部的作用域规则符合您的期望:
Just remember that inside a function you won't use global, since the scope rules inside a function are as you would expect:
请参见该答案,这是在同一代码中使用函数而没有范围问题的一个很好的例子.
See that answer for a good example of using a function for the same code without the scoping problem.
这篇关于Julia 1.0 UndefVarError-变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!