How to return a value from a nested function into main script in Julia?

Viewed 67

For example:

function main()

function doit()
    A = ones(Int, 2) 
    return A
end

doit()
display(A) 
A = [1, 2, 3] 
display(A)
doit()
display(A)

Also what if the nested function has two or three layers, how can we return local variable values into main or save them into main?

1 Answers

Functions in introduce ha hard scope so normally variables defined within them are not seen outside. For your case I understand that you want the function doit() have an external effect of mutating a global variable.

While the use of global variables is discouraged and such side effects are generally not elegant pattern, it can be easily achieved by using global keyword:

function doit()
    global A = ones(Int, 2) 
    return A
end

in that case your Julia session could look like:

julia> doit();

julia> display(A)
2-element Vector{Int64}:
 1
 1

julia> A = [1,2,3];

julia> doit();

julia> display(A)
2-element Vector{Int64}:
 1
 1

For more information, you need to have a look now variable scoping works in Julia: https://docs.julialang.org/en/v1/manual/variables-and-scoping/

Related