Functions
You can write functions in maxscripts. Like C/C++ functions maxscript functions have a name and parameter list. However, it does not have a return type. The function returns whatever the last expression evaluates to in your function body.
You can also explicitly return a value using the return statement. Like C/C++, once a return statement is encountered, statements that follow it in the function are ignored.
Basic syntax:
[mapped] function <functionName> {<parameter list>} = (
<expressions for function body>
)
[mapped] fn <functionName> <parameter list> = (
<expressions for function body>
)
The word mapped in front of the function is optional. If it exists, the function can be applied over a collection such as an array or a set of objects. More details on this will be provided in the array section of the notes
Notice first that you can spell function either as "function" or "fn". There is no difference...
functions can be recursive in nature.
The
By Position
This is the method that you are used to for C/C++ functions. The order of the parameters in your declaration determines how values supplied in the function call are assigned. A parameter of this nature is declared by simply declaring the name of every parameter separated by space.
For example, this function divides 2 numbers
fn doDiv first second = (
first/second
)
/*to call above function, returns 10/2 which is 5 and prints that value*/
a=doDiv 10 2
print a
Note the lack of return statement in the above function. The return is implicitly whatever the expressions in the () evaluate to.
By Keyword
fn doDiv first: second: = (
first/second
)
/*note that in keword style, order has no meaning
so you can put values in whatever order you want*/
a=doDiv second:5 first:10
print a
keyword style parameter lists also allows you to set default values for your parameters
/*default for first is 10, second is 5. If no values are supplied for any of these keywords the default is used*/
fn doDiv first:10 second:5 = (
first/second
)
/*note that in keword style, order has no meaning
so you can put values in whatever order you want*/
a=doDiv
print a
a=doDiv second:3
print a
Mixing position and keyword parameter passing
It is possible to have part of parameter list as positional and part of it as keywords. However, the positional parameters must come first before any of the keyword parameters.
Pass by Reference
As with C, parameter passing is normally pass by value. That is any changes to your parameters do not modify the a variable used by the calling function.
Furthermore, you will also need to indicate you are making a call by reference when you make the function call by prefixing the by reference variable with an &. This is different from how references work in C++ (though sort of similar to C pointers...)
fn passing byValue &byRef = (
byValue = byValue+1
byRef = byRef+1
)
a = 1
b = 1
passing a &b
print a
print b