User defined functions - Crystal Syntax
The content of a user function written in Crystal Syntax is defined as follows
function ( [parameter list] ) //statements//
The statements block can be put into a parentheses block like any other statement block in Crystal Syntax. Like any other Crystal Syntax formula, the return value of the function is defined by the value of the last statement in the formula. Note: since only local variables are allowed, any variable which is declared without scope is a local variable - you don't need to explicitly specify the local scope.
Parameter list
A function can have zero or multiple parameters (which are then comma-separated). The parameter definition is similar to defining a variable without scope. For a function, any parameter is a variable with scope local. A parameter has to be defined as follows
[optional] type [array] [range] name [:= //default//]
term | optional | description |
---|---|---|
optional | X | Indicates that this parameter can be skipped when calling this function. If a parameter is optional, every following parameter has to be optional as well. Furthermore you have to define a default value for any optional parameter. |
type | - | the value type of this parameter |
array | X | marks this parameter as an array type, when combined with range, the type is an array of ranged values |
range | X | marks this parameter as ranged type |
name | - | the name of the parameter, duplicates are not allowed |
:= default | X | the default value, which is required if this parameter is marked as optional. The default is a normal Crystal Syntax but it must have a constant value. This value will be used, if the parameter was left out when calling the function. |
Example
The following example shows a simple add / subtract function for numbers. An optional third parameter switches between add and subtract with add as default. We name this function 'addsubtract'.
function ( numbervar x, numbervar y, optional booleanvar add := true ) if add then x + y else x - y;
These are the results when calling this function
addsubtract( 2, 1 ) ==> 3 addsubtract( 2, 1, true ) ==> 3 addsubtract( 2, 1, false ) ==> 1