如何定义全局变量以稍后在Julia中共享 [英] How to define global variables to be shared later in Julia

查看:75
本文介绍了如何定义全局变量以稍后在Julia中共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件 global.jl 中有一个模块,该模块定义了一个名为数据"的全局多维数组:

I have a module in file global.jl which defines a global multidimensional array named "data":

module Global

    export data

    # GLOBAL DATA ARRAY
    data = zeros(Int32, 20, 12, 31, 24, 60, 5);

end

我有一个 main.jl ,它使用以下全局变量:

I have a main.jl which uses this global variable:

include("global.jl")
using .Global

println(data[14,1,15,18,0,1])

然后出现以下错误:

$ time /usr/local/julia-1.2.0/bin/julia main.jl
ERROR: LoadError: BoundsError: attempt to access 20Ã12Ã31Ã24Ã60Ã5 Array{Int32,6} at index [14, 1, 15, 18, 0, 1]
Stacktrace:
 [1] getindex(::Array{Int32,6}, ::Int64, ::Int64, ::Int64, ::Int64, ::Vararg{Int64,N} where N) at ./array.jl:729
 [2] top-level scope at /usr/home/user/test1/main.jl:4
 [3] include at ./boot.jl:328 [inlined]
 [4] include_relative(::Module, ::String) at ./loading.jl:1094
 [5] include(::Module, ::String) at ./Base.jl:31
 [6] exec_options(::Base.JLOptions) at ./client.jl:295
 [7] _start() at ./client.jl:464
in expression starting at /usr/home/user/test1/main.jl:4

我想我想念如何在Julia中的单独文件中共享全局变量.欢迎任何帮助.

I guess I am missing how to share global variables in a separate file in Julia. Any help is welcomed.

推荐答案

全局很好-您的索引为零,默认情况下,Julia数组索引以1开头,而不是零:

The global is fine--you have a zero index, and Julia array indexes start with 1, not zero, by default:

module Global

    export data

    # GLOBAL DATA ARRAY
    data = zeros(Int32, 20, 12, 31, 24, 60, 5);

end

using .Global

function printplus42()
    println((data .+ 42)[1, 1, 1, 1, 1, :])
end

printplus42()


println(data[14,1,15,18,0,1])

产量:

[42, 42, 42, 42, 42]
ERROR:[...]attempt to access 20×12×31×24×60×5 Array{Int32,6} at index [14, 1, 15, 18, 0, 1]

这篇关于如何定义全局变量以稍后在Julia中共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆