contents   index   previous   next



Function recursion

 

A recursive function is a function that calls itself or that calls another function that calls the first function. Recursion is permitted in ScriptEase. Each call to a function is independent of any other call to that function. (See the section on variable scope.) Be aware that recursion has limits. If a function calls itself too many times, a script will run out of memory and abort.

 

Do not worry if recursion is confusing, since you rarely have to use it. Just remember that a function can call itself if it needs to. For example, the following function, factor(), factors a number. Factoring is an ideal candidate for recursion because it is a repetitive process where the result of one factor is then itself factored according to the same rules.

 

function factor(i) // recursive function to print all factors of i,

{// and return the number of factors in i

   if ( 2 <= i ) 

   {

      for ( var test = 2; test <= i; test++ ) 

      {

         if ( 0 == (i % test) ) 

         {

            // found a factor, so print this factor then call

            // factor() recursively to find the next factor

            return( 1 + factor(i/test) );

         }

      }

   }

   // if this point was reached, then factor not found

   return( 0 );

}

 


Error checking for functions