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:

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:

A special warning to programmers: Since they do not have a stack, other programming languages have probably conditioned you to use locals. With Smojo you need to curb this habit. Locals are usually not needed in Smojo.

Quiz

Question 1

Run the program

1 2 3 add3 .
What is the output?



Question 2

Re-write 
ADD3
without locals. Test your program to make sure it works. Which version do you think is simpler?



Question 3

Re-write 
ADD3&PRINT
without locals. Test your program to make sure it works. Which version do you think is simpler?



Question 4

Refactor 
ADD3&PRINT
. Test your refactored program to make sure it works. Hint: use ADD3



Next: Quotations and Closures