• Tutorials

  • Home
  • GPDL Nested Functions

    DungeonCraft Help Home

    This feature is very much unlike 'C'. GPDL functions can be nested and the nested functions (unlike local variables) can be accessed from anywhere in your program. For example:

      $FUNC  hyptsqu (x , y)  // Square of hypotenuse
      {
        $VARIABLE temp;
        $FUNC  square ( k )
        {
          $RETURN $TIMES ( k, k );
        } square ;
        $RETURN $PLUS(square(x), square(y));
      } hyptsqu ;
      $FUNC  sqP1  ( x )  // x ** 2 + 1
      {   // Square of x plus 1
    
        $RETURN $PLUS(1, hyptsqu@square(x));
      } sqP1 ;

    Notice that:

    function 'square' is nested inside function 'hyptsqu'

    unction 'hyptsqu' references function 'square' as you would expect

    function 'sqP1' can access 'square' from the 'outside'

    The function names are defined in nested dictionaries. When a name such as a@b@c is encountered the search begins by looking for 'a' in the local dictionary and working outward (upward?). When a find is made then the search for 'b' starts in the context of 'a'. Etc.

    In the case of hyptsqu@square, referenced in sqP1, things proceed as follows:

    Look for hyptsqu in sqP1.  No find.
    Look for hyptsqu in next outer function, namely 'root'
    hyptsqu found in root.  Start looking for square in hyptsqu.
    Find successful.

    In order for this to work, it is necessary for nested functions to be unable to reference formal parameters of outer functions. This is because the outer function may never have been called! In the example, 'square' cannot reference the formal parameter 'x' in the function hyptsqu.

    For the same reason, nested functions cannot reference local variables in outer functions. 'square' cannot reference 'temp'.