|REBOL 3 Docs||Guide||Concepts||Functions||Datatypes||Errors|
|TOC < Back Next >||Updated: 6-Feb-2009 Edit History|
The context of variables is called their scope. The broad scope of variables is that of global and local. REBOL uses a form of static scoping, which is called definitional scoping. The scope of a variable is determined when its context is defined. In the case of a function, it is determined by when the function is defined.
All of the local variables defined within a function are scoped relative to that function. Nested functions and objects are able to access their parent's words.
a-func: func [a] [ print ["a:" a] b-func: func [b] [ print ["b:" b] print ["a:" a] print a + b ] b-func 10 ] a-func 11 a: 11 b: 10 a: 11 21
Note here that the b-func has access to the a-func variable.
Words that are bound outside of a function maintain those bindings even when evaluated within a function. This is the result of static scoping, and it allows you to write your own block evaluation functions (like if, while, loop ).
For example, here is a signed if function that evaluates one of three blocks based on the sign of a conditional value:
ifs: func [ "If positive do block 1, zero do block 2, minus do 3" condition block1 block2 block3 ][ if positive? condition [return do block1] if negative? condition [return do block3] return do block2 ] print ifs 12:00 - now/time ["morning"]["noon"]["night"] night
The blocks passed may contain the same words used within the ifs function without interfering with the words defined local to the function. This is because the words passed to the function are not bound to the function.
The next example passes the words block1, block2 and block3 to ifs as pre-defined words. The ifs function does not get confused between the words passed as arguments and the words of the same name defined locally:
block1: "morning right now" block2: "just turned noon" block3: "evening time" print ifs (12:00 - now/time) [block1][block2][block3] evening time
|TOC < Back Next >||REBOL.com - WIP Wiki||Feedback Admin|