Command Set: function

Syntax

{<type>_}function <name> {
    <command_block>
}

Description

Create or redefine a user function.

Parameters

Switches

None

Notes

Within <command_block> the system generic identifier funcval should be used to pass the function value back to the calling command. funcval is treated as a variable-length array to enable multiple values to be returned. Where the function type is not permitted to be an array, e.g. group, funcval is treated as a scalar.

A user function is generally used like a system function, i.e. it returns a value, but it may also be used as a stand-alone procedure, in which case its return value, if set, is discarded. The function does not have to have parameters. A function whose return value is discarded is often referred to as a procedure.

Care should be taken to avoid infinite recursive loops where a function calls itself directly or indirectly.

When a function resides in an atable, the atable is added to the search path for identifiers referenced within the function, with the result that identifiers in the atable may be referenced without an atable prefix.

Caret substitution will be performed at function execution time. For caret substitution to be performed at definition time, begin a command in command_block with a / to expand ^(...) phrases on that particular line.

A function whose <command_block> contains only args statements and comments is treated as empty or null.

Examples

A function to compute the sum of the series 1 through n.

function series_sum {
    args n=numeric
    funcval = n
    while (n > 1) {
        n--
        funcval = funcval + n
    }
}

Example use of the function.

numeric x; ask 'Give number',x
tell <'Series sum is',series_sum(x)>

A function to compute a point third distance between two other points along the x axis.

point_function third {
    args p1=point, p2=point
    funcval.x = p1.x * 2/3 + p2.x / 3
    funcval.y = p1.y
    funcval.z = p1.z
}

Example use of the function.

point my_point = third(gc,pcur)

A function to prompt the user for a string value.

string_function qstring {
    args prompt=string
    ask prompt,funcval
}

Example to rename an entity with a user-given name.

ep.name = qstring('Give it a name')

See Also

Commands:

args, exec, procedure

Identifiers:

funcval (generic), scope (atable)