MAXScript supports by-reference parameter passing. This allows a reference to be passed to a variable, property, or array element in the caller's context as a parameter to a function and any assignments to that parameter in the called function is assigned directly to the caller's variable, property, or array element. This is often used as a mechanism for passing multiple results back from a function.
To define by-reference parameters for a function, you need to prefix them with an '&' character.
System Exception Note:
The following example is an error:
ERROR EXAMPLE
fn test1 &p3 = return &p3.x p=[1,2,3] r=test1 p *r
Result: access violation!
It is an error to pass back a reference to a local that has gone from the call stack, but it is very difficult to detect this efficiently. Be careful not to pass back &refs
to local variables as it might cause system exceptions.
EXAMPLE
function foo x y &z = ( -- ... z = x * y -- ... return true ) -- test function z = 12 foo 5 6 &z
Declares a function taking three parameters, x, y and z. The
&z
in the parameter list indicates the z parameter is to be passed by-reference. To call this function, you provide a reference value for the z parameter using the new '&' reference operator.local var1, var2 ... var1 = foo 2 3 &var2
The above example calls the foo function with the arguments 2, 3 and
&var2
. The&var2
is a reference to the var2 local variable. When the function is called, the z parameter in the body is a reference tovar2
local in the caller, and thez = x * y
in the body of foo will cause x * y to be assigned to the
var2
local in the caller. Aftervar1 = foo 2 3 &var2
var1
will containtrue
andvar2
will containx * y
or6
.
Any number of by-reference parameters can be used and they can be keyword parameters if needed:
fn foo x y &z: = ...
called like this:
var1 = foo 2 3 z:&var2
The ' &
' reference operator used to supply references in a call can be applied to any <accessor>
construct in MAXScript. These are:
variables (locals, globals, rollout locals, plug-in locals, etc.)
property access
array index
parameter (of a scripted plug-in)
EXAMPLE
p = [1, 2, 3] foo 2 3 &p.x
would cause the x coordinate in the point to be passed by-reference and so after the call, the value in p would be
[6, 2, 3]
EXAMPLE
a = #(1, 2, 3, 4, 5) foo 2 3 &a[3]
would cause the 3rd element in the array to be passed by-reference and so after the call, the value in a would be #(1, 2, 6, 4, 5)
This mechanism is used by the Function Publishing interface in MAXScript to support BY-REF interface method parameters and results. Any parameter defined as by-ref (or with a type code suffix _BR) in the published interface, requires an '&' reference value.