Function definitions

Provides a reference for the syntax of function definitions in OPL.

Table 1. Function definition syntax
Syntax Effect

[ static ]

function name(v1, ..., vn)

{statements}

Defines a function name with the given parameters and body. A function definition can only take place at the top level; function definitions cannot be nested.

When the function is called, the script variables v1, ..., vn are set to the corresponding argument values, then the statements are executed. If a return statement is reached, the function returns the specified value; otherwise, after the statements are executed, the function returns the undefined value.

The number of actual arguments does not need to match the number of parameters: if there are fewer arguments than parameters, the remaining parameters are set to the undefined value; if there are more arguments than parameters, the excess arguments are ignored.

Independently of the parameter mechanism, the function arguments can be retrieved using the arguments keyword described in Table 1.
return [ expression ] Returns the value of expression from the current function. If expression is omitted, returns the undefined value. The return statement can only be used in the body of a function.

Defining a function name is operationally the same as assigning a specific function value to the variable name; thus a function definition is equivalent to:


var name = some function value 

The function value can be retrieved from the script variable and manipulated like any other type of value. For example, the following program defines a function add and assigns its value to the variable sum, which makes add and sum synonyms for the same function:


function add(a, b) {
  return a+b
}

var sum = add(1, 2);

Without the keyword static, the defined function is global and can be accessed from the whole application. With the keyword static, the function is local to the current program unit, exactly as if name was declared with the keyword var :


var name = some function value