Locals
As a rule of thumb, your words should not use more than 2 or 3 items on the stack. With these few items to use, you can simply use stack words (DUP,
SWAP,
OVER, etc.) to get the result you want.
However, in some cases it is often helpful to assign names to items on the stack. A program to illustrate this idea:
: double ( n -- n ) { x } x x +. ;In this example, I've assigned the name X to the top of the stack. This assignment actually pops the stack, and binds the item to the local X. The word
{begins a set of assignments, and you can bind more than one item :
: add3 ( n n n -- n ) { a b c } a b +. c +. ;The assignments stop at the closing
}.
Such assignments of items on the stack to names, are called locals. A few things to note:
- The items are popped off the stack by
{
, assigning them to your locals until the closing}
is encountered. - Locals are only valid in the immediate environment of the Word in which they are made. That's why they are called "locals", because they are local to the word in which they are defined.
- You may create locals anywhere within your Word's definition. For example:
: add3&print ( n n n -- n ) { a b c } a b +. c +. { x } x . ;
A Warning!
Try not to use locals. Their usage often makes simple code complex. Locals also result in slower programs than using Stack Words. A couple of guidelines:
- If your word uses more than 3 items on the stack, that is sometimes a sign that your program is badly designed. Try to split your word into multiple words, each using 3 items or less from the stack. This process is called refactoring .
- Ask yourself the use/non-use of locals makes your Word easier to understand. Always strive for clarity.
Quiz
Question 1
Run the program
1 2 3 add3 .What is the output?
6.0
Question 2
Re-writeADD3without locals. Test your program to make sure it works. Which version do you think is simpler?
: add3 ( n n n -- n ) +. +. ; 1 2 3 add3 . \ 6.0
Question 3
Re-writeADD3&PRINTwithout locals. Test your program to make sure it works. Which version do you think is simpler?
: add3&print ( n n n -- n ) +. +. . ; 1 2 3 add3&print \ 6.0
Question 4
RefactorADD3&PRINT. Test your refactored program to make sure it works. Hint: use ADD3
: add3&print ( n n n -- n ) add3 . ; 1 2 3 add3&print \ 6.0