未在Julia中定义的全局变量 [英] Global variable not defined in Julia
问题描述
以前曾在此处提出过类似的问题,但根据该问题的答案和Julia手册,以下.jl脚本应该可以使用.
A similar question has been previously asked here, but according to the answer to that question and the Julia manual, the following .jl script should work.
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
我显式声明了全局变量,然后尝试在函数内部对其进行修改.但是,当我尝试运行函数test1()时,它说该变量未定义.
I explicitly declare a variable global and then try to modify it inside a function. However when I attempt to run the function test1(), it says that the variable is undefined.
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);
有人知道我在做什么错吗?
I've tried different things, and it does work if I just access the variable in test1(), like print(myVar);
Does anyone know what I'm doing wrong?
推荐答案
我认为您需要将global
放在需要访问全局变量的函数中.
I think you need to put global
inside the function that needs to access the global variable.
以下对我有用:
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
这篇关于未在Julia中定义的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!