Julia Variable scope

2019-07-10 17:02发布

问题:

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

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

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

The code works with julia 0.7.0, but why doesn't it work with version 1.0.0 ?

回答1:

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

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.

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.



回答2:

Have you actually tried declaring the variables on the top of your code module as per the warning messages like so?

global r
global m
global n

Welcome to Stackoverflow!