GENERATE/PREV.gifGENERATE/NEXT.gif

Function Definition

Functions can be defined in MAXScript using the function definition expression, <function_def>. The syntax is:

(function | fn) <name> { <parameter> } = <expr>

in which <name> is the name of the function, the optional sequence of <parameter>'s can be one of:

<name>

<name>: [ <operand> ]      -- keyword parameter with optional default value

and the <expr> after the '=' equal sign is the body of the function.

The function <name> is actually used to name a global variable into which a value representing the function is placed. When you call a function by using its name, you are accessing its definition in a global variable of that name.

The parameters for a function are either positional or keyword. Positional parameters are defined with a simple <name> and must come before any keyword parameters. Keyword parameters have a ':' colon after the name and an optional default value. The caller of the function can optionally supply keyword arguments in any order, and those not supplied will be set to the default value given, or the special value unsupplied, if a default value is not given.

Examples:

function add a b = a + b

fn factorial n = if n <= 0 then 1 else n * factorial(n - 1)

fn starfield count extent:[200,200,200] pos:[0,0,0] =

(

local f = pos - extent / 2,

t = pos + extent / 2

 

for i = 1 to count do

sphere name:"star" \

radius:(random 0.1 2.0) \

position:(random f t) \

segs:4 smooth:false

)

A scripted function returns as its value the value of the body <expr>. If the body is a block expression, the function evaluates to the value of the last expression in the block.

A function can be defined recursively, as is the factorial function in the examples above.

Note: Prior to this release, MAXScript classed all user-scripted functions as mapped, which meant that they were always automatically called repeatedly on the elements of a collection if the collection was given as the first argument to the function. This has been the cause of several obscure bugs in testers' scripts, so the default now is that user-scripted functions are not automatically mapped (in other words, a collection first argument is passed along as a collection to a single call of the function).

You can define mapped functions by preceding the definition with the new reserved word mapped, for example:

mapped function rand_color x =

x.wireColor = random (color 0 0 0) (color 255 255 255)

Note that this requires a change to the main demo file demo.ms. The updated file is in the 0.2.16 samples folder available in the Compuserve scripter library.

See also:

Function Variables

Parameters

The Return Expression