ForthOS Local Variables


ForthOS intentionally departs from the direction of ANSI Forth in its implementation of "local variables". In ForthOS, it is really more correct to call the facility "local constants". Examples are probably the easiest way to understand the facility.

Local Constants

	: sum+1 { a1 a2 }   a1 a2 + { sum }   sum 1+ ;

Braces specify the cells on the stack. Each cell is popped off the stack and its value made available as the named argument. The scope of such names is through the end of the function. As can be seen in the example, successive names can be added as further constant values are identified.

Return Values (with stack format enforcement)

   : sum+1 { a1 a2 -- result }   a1 a2 + { sum }   sum 1+ ;

This definition is very similar to the previous, except that the initial definition of local values has a "-- result" added. "result" is not an identifier in the scope of the function, however ForthOS records that this function took two arguments and returns a single value. On exit of the function, if the stack has not changed in the expected way, an abort is thrown.

Variable Return Formats

	: maybe { val -- val' T | F }   val 0 > if   val 1+ true
	      else   false then ; 

In this variation, "val' T | F" indicates that it is legal for the function to return one or two arguments. Actual values are not enforced.