全局变量未在Julia中定义

use*_*829 3 julia

此处已经提出类似的问题,但根据该问题的答案和Julia手册,以下.jl脚本应该可以正常工作.

global myVar = spzeros(10,1);
myVar[3] = 1;

function test_base()
  test1();
end

function test1()
  myVar = [ i > 0 ? 2 : 0 for i in myVar] #doesn't work
end
Run Code Online (Sandbox Code Playgroud)

我明确声明一个变量global,然后尝试在函数内修改它.但是,当我尝试运行函数test1()时,它表示变量未定义.

julia> VERSION
v"0.3.5"

julia> include("test.jl")
test1 (generic function with 1 method)

julia> test_base()
ERROR: myVar not defined
 in test1 at /home/clifton/Julia/ca-1/test.jl:9
 in test_base at /home/clifton/Julia/ca-1/test.jl:5
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的东西,如果我只是访问test1()中的变量,它确实有效,就像print(myVar);有人知道我做错了吗?

spe*_*on2 8

我认为你需要放入global需要访问全局变量的函数.

以下适用于我:

myVar = spzeros(10,1);
myVar[3] = 1;

function test_base()
    test1();
end

function test1()
    global myVar
    myVar = [ i > 0 ? 2 : 0 for i in myVar] #doesn't work
end
Run Code Online (Sandbox Code Playgroud)

输出:

julia> include("test.jl")
test1 (generic function with 1 method)

julia> test_base()
10-element Array{Int64,1}:
 0
 0
 2
 0
 0
 0
 0
 0
 0
 0
Run Code Online (Sandbox Code Playgroud)