Defining a Function

A function is a program unit containing one or more IDL statements that returns a value. This unit executes independently of its caller. It has its own local variables and execution environment. Referencing a function causes the program unit to be executed. All functions return a function value which is given as a parameter in the RETURN statement used to exit the function. Function names can be up to 128 characters long.

The general format of a function definition is as follows:

FUNCTION Name, Parameter1, ..., Parametern 
    Statement1 
    Statement2 
    ... 
    ... 
    RETURN, Expression 
END 

Function Example

To define a function called AVERAGE, which returns the average value of an array, use the following statements:

FUNCTION AVERAGE, arr 
    RETURN, TOTAL(arr)/N_ELEMENTS(arr) 
END 

Once the function AVERAGE has been defined, it is executed by entering the function name followed by its arguments enclosed in parentheses. Assuming the variable X contains an array, the statement,

PRINT, AVERAGE(X^2) 

squares the array X, passes this result to the AVERAGE function, and prints the result. To return the result in a variable, use a function call as follows:

vAvg = AVERAGE(X^2) 

Parameters passed to functions are identified by their position or by a keyword. See Using Keyword Parameters. If a function has no parameters, you must specify empty parentheses in the function call.