Using Nasal functions: Difference between revisions

Jump to navigation Jump to search
Argument passing by value / by reference
(Argument passing by value / by reference)
Line 311: Line 311:


Also note that the standard arg vector, including its ellipsis form, is no longer available when using a hash to initialize the parameters of a function call.
Also note that the standard arg vector, including its ellipsis form, is no longer available when using a hash to initialize the parameters of a function call.
=== Argument passing by value / by reference ===
If you pass an argument to a function you must consider its type (see [[Typeof]]). If you pass a scalar (string, number), it will be passed '''by value''', if you pass a hash or vector, it will be passed '''by reference'''.
This means:
# If you change an argument variable in your function that was passed '''by value''' (copied), the variable outside the function will stay unchanged.
# If you change an argument variable in your function that was passed '''by reference''' (same memory), the value outside the function '''will change'''.
<syntaxhighlight lang="nasal">
var add1 = func(myScalar) {
  myScalar = myScalar + 1;
  return myScalar;
}
var set42 = func(myVector) {
  myVector[0] = 42;
}
var a = 1;
print(a);
print(add1(a)); # this prints the return value of the function call!
print(a);      # variable a outside the function shall be still 1
var b = [1,2,3];
print(debug.string(b));
print(set42(b));        # print the return value which is 42
print(debug.string(b));  # now b[0] has changed
</syntaxhighlight>


== Nested functions, implicit return ==
== Nested functions, implicit return ==
252

edits

Navigation menu