Reputation: 8117
I have a function
function foo(a)
if a > 5
a = 5
end
some_more_code
end
If the if
-statement is true
I would like to end the function but I don't want to return anything - to change the value of a
is all I need.
How do I do that?
Upvotes: 3
Views: 694
Reputation: 69899
You can write (note that I have also changed the syntax of function definition to make it more standard for Julia style):
function foo(a)
if a > 5
a = 5
return
end
# some_more_code
end
Just use the return
keyword without any expression following it. To be precise in such cases Julia returns nothing
value of type Nothing
from a function (which is not printed in REPL and serves to signal that you did not want to return anything from a function).
Note though that the value of a
will be only changed locally (within the scope of the function), so that outside of the function it will be unchanged:
julia> function foo(a)
if a > 5
a = 5
return
end
# some_more_code
end
foo (generic function with 1 method)
julia> x = 10
julia> foo(x)
julia> x
10
In order to make the change visible outside of the function you have to make a
to be some kind of container. A typical container for such cases is Ref
:
julia> function foo2(a)
if a[] > 5
a[] = 5
return
end
# some_more_code
end
foo2 (generic function with 1 method)
julia> x = Ref(10)
Base.RefValue{Int64}(10)
julia> foo2(x)
julia> x[]
5
Upvotes: 7