REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 6-Feb-2009 Edit History  

REBOL 3 Concepts: Functions: Nested Functions

Pending Revision

This document was written for R2 and has yet to be revised for R3.

Functions can define other functions. The sub-functions can be global, local, or returned as a result, depending on their purpose.

For example, to create a global function from within a function, assign it to a global variable:

make-timer: func [code] [
    timer: func [time] code
]
make-timer [wait time]
timer 5

To make a local function, assign it to a local variable:

do-timer: func [code delay /local timer] [
    timer: func [time] code
    timer delay
    timer delay
]
do-timer [wait time] 5

The timer function only exists during the period when the do-timer function is being evaluated.

To return a function as a result:

make-timer: func [code] [
    func [time] code
]
timer: make-timer [wait time]
timer 5
Use Correct Local Variables

You should avoid using variables that are local to the top level function as an unevaluated part of the nested function. For example:

make-timer: func [code delay] [
    timer: func [time] [wait time + delay]
]

In the example, the delay word dynamically belongs to the make-timer function. This should be avoided, as the delay value will change in subsequent calls to make-timer.


  TOC < Back Next > REBOL.com - WIP Wiki Feedback Admin