Skip to main content

This is documentation for Caché & Ensemble. See the InterSystems IRIS version of this content.

For information on migrating to InterSystems IRIS, see Why Migrate to InterSystems IRIS?

User-Defined Functions

In the first chapter, you learned about procedures, and in this chapter, you've learned about the functions that ObjectScript provides. They are called system-defined functions, to differentiate them from functions that you can write yourself, called user-defined functions. These are simply procedures that return a result. Within the function, you specify the value that the function should return as the argument of the Quit.

You use user-defined functions like system-defined functions, except that you use $$ before the function name.

SAMPLES>do ^funcexample

Enter a number: 4
The factorial of 4 is 24
SAMPLES>do ^funcexample

Enter a number: 5
The factorial of 5 is 120
SAMPLES>write $$fact^funcexample(6) ; call it directly
720
SAMPLES>

The funcexample.mac code:

funcexample ; example of user-defined function
    read !, "Enter a number: ", num
    set fact = $$fact( num )
    write !, "The factorial of ", num, " is ", fact
    quit
fact(number) PUBLIC
    ; compute factorial
    {
    if number < 1 {quit "Error!"}
    if (number = 1) || (number = 2) {quit number}
    set x = number * $$fact( number - 1 )
    quit x
    }
Feedback