Passing Arguments by Reference
By default, arguments to class methods are passed by value. That means that the class method receives the value of the variable passed into it, and any modifications of the value are private, only visible within the method—the value of the original variable outside the method is not changed. The first part of the example, DoubleByVal(), uses the num variable to compute its double, but the num variable, outside the class method, is not changed.
ObjectScript also allows you to pass arguments by reference, which means that when the class method modifies the value of the variable, it's modifying the value of the variable outside the method—both variables reference the same memory location. Passing arguments to a class method by reference only works if you precede these arguments with a dot. Passing an array to a method requires passing it by reference, using the dot.
The DoubleByRef1() class method changes num into its double because of the dot preceding num. The ByRef in the method signature is only a reminder to the caller to use the dot.
The DoubleByRef2() class method returns the double of num by creating result, preceding it with the dot. The Output in the method signature is only a reminder to the caller to use the dot.
Examples of passing arguments:
VS Code - ObjectScript
/// examples for ObjectScript Tutorial
/// demo of passing arguments by value and reference
ClassMethod PassingArguments(num as %Numeric)
// pass by value
set dblnum = ..DoubleByVal(num)
write !, "By Value: ", num, " doubled is: ", dblnum
// num passed IN and OUT by reference
write !, "By Reference 1: ", num
write " doubled is: ", num
// num passed IN by value, result passed OUT by reference
do ..DoubleByRef2(num, .result)
write !, "By Reference 2: ", num, " doubled again is: ", result
ClassMethod DoubleByVal(anynumber as %Numeric) as %Numeric
return anynumber * 2
ClassMethod DoubleByRef1(ByRef anynumber as %Numeric)
set anynumber = anynumber * 2
ClassMethod DoubleByRef2(anynumber as %Numeric, Output retnumber as %Numeric)
set retnumber = anynumber * 2
Testing using the Terminal
By Value: 3 doubled is: 6
By Reference 1: 3 doubled is: 6
By Reference 2: 6 doubled again is: 12