Previous: , Up: Function Call   [Contents][Index]


6.4.2 Recursion

Recursion is the act of calling a routine (subroutine or function) as part of its own execution. Recursion is allowed for all routines in LUX, whether they are built-in or user-defined.

The parameters of a user-defined routine are independent from instance to instance: If more than one instance of a particular user-defined routine is active at the same time, then a particular parameter in one copy of the routine is independent of the version of the same parameter in all other copies of the routine. However, the values of the parameters are lost when the routine is finished.

The strictly local variables of the routine are not covered by this rule: only a single copy of such variables exists, which is shared between all instances of the routine, and which retains its value even after the routine is finished.

It is quite easy to define a function or subroutine that keeps calling itself indefinitely. LUX leaves checking for such infinite recursion up to the user.

For example, here is a definition for a function that calculates the factorial of a positive integer number n (i.e., the product of all numbers between 1 and n, inclusive):

func fac(n)
  if n eq 1 then return,n
  return,n*fac(n-1)
endfunc

If we call this function with argument 3, then foo(3) calls foo(2), which calls foo(1). When foo(1) is being evaluated, three instances of foo() are active at the same time, each with their own independent copy of n.

In this particular example, the function is not waterproof against infinite recursion. If you call the function with a number smaller than 1, or with a number that is not an integer, then it will keep calling itself indefinitely until all those different instances of foo() fill up LUX’s symbol tables.


Previous: , Up: Function Call   [Contents][Index]