User Defined Procedures in Comet32 (Procs)
May be subroutines or functions. A Proc may or may not return a value. Procs that return a value are called Functions and those that do not are called subroutines.
Functions may be numeric or string depending on the kind of result they return. Functions may be called anywhere a system function is called. Subroutines are invoked with the CALL verb (Not GOSUB).
Procs must be declared in the main program. Just like variables, Procs must be declared before use. In fact, they must be declared in the Main part of the program. Procs may take arguments and have locally defined local variables. The body of a proc looks like a mini program. It has a declaration section and an executable section. All locals declared in the proc except for arguments are cleared. A clear local statement is not required. Procs inherit all system variables and all variables declared in the main program. If a variable name is not found in the local declarations for a proc, and the variable is declared in the main program, that variable is used by the proc. In this case, the variable is used BY REFERENCE; that is, if the proc changes the variable, it is changed for the main program as well.
Arguments may be passed by value or by reference. If an argument to a proc also appears in the declarations of local for the proc, the argument is copied into that local variable. If an argument does not also appear as a local variable, it as passed by reference. When a variable is passed by reference, no copy action is done (better performance), and the contents of the variable may be changed for the calling routine as well as for the proc. Procs can call procs and may be recursive. Each time a proc is called; new storage for the proc is created. The arguments are then passed, initializing some of that storage. When a ProcReturn is executed, all local storage for that instance of the proc is destroyed. This provides a mechanism for recursion. An example:
! Declare Subroutines And Functions
Numeric Factor(n) length 32.0 & local i z print (et) . fact: print 'factorial of what?' input i if i > 29 print 'Warning -- factorial of a number > 29 will overflow' & wait if i = 0 stop !! Z = Factor(I) ! Call our function here !! Print i;' Factorial Is ' ! Iterate through the function to get the factorial Print z Wait z = Factorial(I) ! use the math library to get the factorial for validation purposes Print z wait goto fact end
! Called Function
Numeric Factor(n) Length 32.0 & Local x print 'fact';n if n <= 1 Procreturn 1 print 'returning ';n &wait x = n - 1 Procreturn Factor(x) * n ! Calling myself End