2015-02-10 141 views
2

以前有人问过类似的问题here,但根据对该问题和Julia手册的回答,下面的.jl脚本应该可以工作。Julia中没有定义全局变量

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 

我明确声明了一个变量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 

我已经尝试不同的东西,如果我只是访问变量test1的(),像print(myVar);有谁知道我做错了它的工作?

回答

6

我想你需要把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 

输出:

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