【问题标题】:Global variable not defined in Julia全局变量未在 Julia 中定义
【发布时间】:2015-02-10 05:02:30
【问题描述】:

之前有人问过here 类似的问题,但根据该问题的答案和 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

我显式声明了一个全局变量,然后尝试在函数中对其进行修改。但是,当我尝试运行函数 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); 有人知道我做错了什么吗?

【问题讨论】:

    标签: julia


    【解决方案1】:

    我认为您需要将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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 2019-04-08
      • 2018-09-17
      相关资源
      最近更新 更多