Julia 变量范围 [英] Julia Variable scope
问题描述
我正在尝试在 while 循环中使用一些全局变量(m、n、r),但 julia 1.0.0 告诉我这些变量没有定义.该代码适用于 julia 0.7.0,但有一些警告.这是我正在使用的代码(是的,它写得不好,我希望这不是问题.为了简单起见,我删除了 println
语句):
I'm trying to use some global variables (m, n, r) in a while loop, but julia 1.0.0 is telling me that those variables aren't defined. The code works with julia 0.7.0, with some warnings.
This is the code I'm using (yes, it's poorely written, I hope this is not the problem. I removed a println
statement for the sake of simplicity):
m = readline()
n = readline()
m = parse(Int, m)
n = parse(Int, n)
r = m % n
while (r > 0)
println( "m: $(m) n: $(n) r: $(r)" )
r = m % n
m = n
n = r
end
这是 julia 1.0.0 的结果:
This is the results with julia 1.0.0:
ERROR: LoadError: UndefVarError: m not defined
Stacktrace:
[1] top-level scope at euclide.jl:11 [inlined]
[2] top-level scope at ./none:0
[3] include at ./boot.jl:317 [inlined]
[4] include_relative(::Module, ::String) at ./loading.jl:1038
[5] include(::Module, ::String) at ./sysimg.jl:29
[6] exec_options(::Base.JLOptions) at ./client.jl:229
[7] _start() at ./client.jl:421
in expression starting at euclide.jl:10
还有 Julia 0.7.0:
And with julia 0.7.0:
┌ Warning: Deprecated syntax `implicit assignment to global variable `r``.
│ Use `global r` instead.
└ @ none:0
┌ Warning: Deprecated syntax `implicit assignment to global variable `m``.
│ Use `global m` instead.
└ @ none:0
┌ Warning: Deprecated syntax `implicit assignment to global variable `n``.
│ Use `global n` instead.
└ @ none:0
该代码适用于 julia 0.7.0,但为什么不适用于 1.0.0 版本?
The code works with julia 0.7.0, but why doesn't it work with version 1.0.0 ?
推荐答案
你必须声明你在全局范围内定义的变量,并在循环局部范围内赋值给为global
在这样的循环内:
You have to declare variables you define in global scope and assign to in loop local scope as global
inside the loop like this:
m = readline()
n = readline()
m = parse(Int, m)
n = parse(Int, n)
r = m % n
while (r > 0)
println( "m: $(m) n: $(n) r: $(r)" )
global r = m % n
global m = n
global n = r
end
你必须这样做的原因是 while
循环引入了一个新的本地范围,所以没有像 m = n
这样的 global
关键字分配告诉 Julia m
是 while
循环内的局部变量,因此在 println("m: $(m) n: $(n) r: $(r)" )
Julia 确定 m
尚未定义.
The reason you have to do it is that while
loops introduce a new local scope, so without global
keyword assignment like m = n
tells Julia that m
is a local variable inside a while
loop so then in the line println( "m: $(m) n: $(n) r: $(r)" )
Julia decides that m
is yet undefined.
另请参阅 https://docs.julialang.org/en/latest/manual/variables-and-scoping/ 和 为什么在 Julia 0.7 和 1.0 中循环内的赋值失败? 进一步解释 Julia 中的范围规则.
See also https://docs.julialang.org/en/latest/manual/variables-and-scoping/ and Why does this assignment inside a loop fail in Julia 0.7 and 1.0? for further explanation of the scoping rules in Julia.
这篇关于Julia 变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!