Global variable not defined in Julia

人走茶凉 提交于 2020-12-29 06:58:30

问题


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

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

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?


回答1:


I think you need to put global inside the function that needs to access the global variable.

The following works for me:

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

Output:

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


来源:https://stackoverflow.com/questions/28424470/global-variable-not-defined-in-julia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!