next up previous contents index
Next: The exec Keyword Up: The Xic Scripting Language Previous: Math Functions   Contents   Index


User-Defined Functions

In scripts, user-defined functions are supported. The function must be defined before it is called.

A function definition starts with the keyword function, followed by the function name and argument list. The keyword endfunc terminates the definition. These blocks can appear anywhere between statements in a script file, however they must appear before any calls to the function. Once a function has been parsed, it is added to an internal database, where a compiled representation is retained. If the same function is parsed again, the in-memory representation is updated. There is a mechanism for automatically loading libraries (see 18.2) of script functions at program startup. Use of this mechanism avoids the overhead of repeatedly parsing function definitions that are found in script files.

The function is called just like a built-in function. Scalar variables are passed by value, other types are passed to the function by reference. Variables defined within a function are automatic by default.

Functions can return a value. In a function, the construct

return [expression]
can be used to terminate execution, and the value of the expression is returned by the function. The value returned can be of any type. If the return value is a local string, the string will be copied. If the return value is a pointer to an array, the array must have been passed as an argument or have been declared static or global (see 18.12).

The example below illustrates how variables are passed, and the scope for changes. Strings and arrays can not be redefined in a function, but elements can be changed. Arrays are used to pass results back to the calling function.

Example:

function myfunc(a, b, c)
Print(a, b, c)
endfunc

function examp(a, b, c)
# a is a constant, can be redefined within the scope of examp
a = 2
# b is a string, it is an error to redefine, but can be altered, in
# which case the string is altered in the calling function as well
#b = "b string"   (this produces an error)
b[2] = 'x'
# c is an array, it is an error to redefine, but elements can be
# changed, in which case this is reflected to all users of the array
# c[3]  (redefinition, this is an error)
c[1] = 1.234
myfunc(a, b, c)
endfunc

Print("this is a test")
x = 1
y = "a string"
z[2]
myfunc(x, y, z)
examp(x, y, z)
myfunc(x, y, z)

It is presently not possible to single-step through a function in the Script Debugger.


next up previous contents index
Next: The exec Keyword Up: The Xic Scripting Language Previous: Math Functions   Contents   Index
Stephen R. Whiteley 2024-09-29