Dict get destroys global variable?

75 views
Skip to first unread message

K leo

unread,
Sep 22, 2016, 11:52:24 PM9/22/16
to julia-users
Calling "get" anywhere in a function makes a global variable undefined.  Can anyone please help explaining the following?

1) without calling "get", the global variable is fine:

a=0
Dicta = Dict{Int,Int}()
function testGlobal()
    println(a)
    merge!(Dicta, Dict(1=>1))
#     a=get(Dicta, 1, 0)
    println(a)  
    nothing
end

julia> testGlobal()
0
0

2) calling "get" (same code as above except uncommenting the "get" statement) and the global variable becomes undefined:

a=0
Dicta = Dict{Int,Int}()
function testGlobal()
    println(a)
    merge!(Dicta, Dict(1=>1))
    a=get(Dicta, 1, 0)
    println(a)  
    nothing
end

julia> testGlobal()
ERROR: UndefVarError: a not defined
 in testGlobal() at /xxx/testType.jl:4

3) not calling the first println, the code works, but the global a is not set:

a=0
Dicta = Dict{Int,Int}()
function testGlobal()
#     println(a)
    merge!(Dicta, Dict(1=>1))
    a=get(Dicta, 1, 0)
    println(a)  
    nothing
end


julia> testGlobal()
1


K leo

unread,
Sep 23, 2016, 12:00:37 AM9/23/16
to julia-users
Sorry, this is not related to Dict at all.  If I replace the "a=get..." statement with simply "a=2", the global variable is no longer accessible.  What is wrong?

Isaiah Norton

unread,
Sep 23, 2016, 12:06:17 AM9/23/16
to julia...@googlegroups.com
Use `global a = ...`
Please see: http://docs.julialang.org/en/latest/manual/variables-and-scoping/#hard-local-scope

global variables are only inherited for reading but not for writing

 

K leo

unread,
Sep 23, 2016, 12:46:54 AM9/23/16
to julia-users
Thank you Isaiah for pointing that out!
Reply all
Reply to author
Forward
0 new messages