Function Variables

When you define a function, the following events occur:

Because the function itself is a value stored in a variable, you not only can call the function through the function name variable. By simply referring the function's variable you can also assign the function value to another variable, store it in an array, or pass it as an argument to another function.

Example

-- some 3D surface functions

fn saddle x y = sin x * sin y

fn sombrero x y = cos (x^2 + y^2) / (1 + (x^2 + y^2))

print (saddle 1 1) -- try one out

surface_functions[1] = saddle -- store the functions in an array

surface_functions[2] = sombrero

z = (surface_functions[i]) 10 10 -- call one of them from within

-- the array

build_math_mesh sombrero -- pass one in to a higher-order

-- function

The scope of a function variable is the current MAXScript scope context. The variables used inside a function have a local scope, unless the variable was already defined at a higher scope or is declared as global in the function. An exception to this is the function parameter variables, which always have a local scope.

When writing scripts, it is good programming practice to explicitly declare your local and global variables. Implicit declaration is provided as a short-hand, typically used when working in the Listener interactively or developing short scripts. When developing extended scripts, explicitly declaring variables can reduce errors and improve readability of the code. It is also recommend that you declare as local all variables unless you really want them to be global variables. The reasons for this are described in Scope of Variables.

If a function variable is assigned to another variable, a reference to the function value is stored in that variable. Thus while a function variable may no longer be in scope, the function itself still is if the variable it is assigned to has a scope that extends outside the current MAXScript scope context.

Examples

fn funcA which =

(

if which == 1 then

fn saddle x y = sin x * sin y

else

fn sombrero x y = cos (x^2 + y^2) / (1 + (x^2 + y^2))

)

myfunc=funcA 2

z=myfunc 10 10

In the above example, the scope of variables saddle and sombrero is local to funcA, and the variables are out of scope outside the function. The return value of funcA is either the function value saddle() or sombrero(), and is assigned to variable myfunc. As also can be seen in this example, you can define a function within any expression.

See also

Scope of Variables

Function Calls