logankilpatrick
logankilpatrick

Reputation: 14501

Using global variables in a function in Julia

how do I create/use a global variable inside of a function?

If I make the Global variable in one function, how do I reference it in a subsequent function?

Upvotes: 1

Views: 1869

Answers (1)

logankilpatrick
logankilpatrick

Reputation: 14501

Here is what you would need to do:

function a()
    global z = 0
    print(z)
end

function b()
    global z += 1
    print(z)
end

Note that in Function b, if you do not reference z as global z, it will look in the local scope of the function where there is no z variable defined and give an error:

julia> b()
ERROR: UndefVarError: z not defined

julia> a() # defines z in global scope
0

julia> b() # works now because z has been defined
1

Edit: As Michael pointed out in the comment below, it is not generally a good idea to use this sort of global paradigm in practice. This can result in code that is difficult to debug, understand, and potentially invalid outputs.

Upvotes: 2

Related Questions