Next: , Previous: , Up: Locals   [Contents][Index]

5.21.1 Gforth locals

Locals can be defined with

{ local1 local2 ... -- comment }


{ local1 local2 ... }


: max { n1 n2 -- n3 }
 n1 n2 > if
 endif ;

The similarity of locals definitions with stack comments is intended. A locals definition often replaces the stack comment of a word. The order of the locals corresponds to the order in a stack comment and everything after the -- is really a comment.

This similarity has one disadvantage: It is too easy to confuse locals declarations with stack comments, causing bugs and making them hard to find. However, this problem can be avoided by appropriate coding conventions: Do not use both notations in the same program. If you do, they should be distinguished using additional means, e.g. by position.

The name of the local may be preceded by a type specifier, e.g., F: for a floating point value:

: CX* { F: Ar F: Ai F: Br F: Bi -- Cr Ci }
\ complex multiplication
 Ar Br f* Ai Bi f* f-
 Ar Bi f* Ai Br f* f+ ;

Gforth currently supports cells (W:, W^), doubles (D:, D^), floats (F:, F^) and characters (C:, C^) in two flavours: a value-flavoured local (defined with W:, D: etc.) produces its value and can be changed with TO. A variable-flavoured local (defined with W^ etc.) produces its address (which becomes invalid when the variable’s scope is left). E.g., the standard word emit can be defined in terms of type like this:

: emit { C^ char* -- }
    char* 1 type ;

A local without type specifier is a W: local. Both flavours of locals are initialized with values from the data or FP stack.

Gforth supports the square bracket notation of local data structures. These locals are similar to variable-flavored locals, the size is specified as a constant expression. A declaration looks name[ size ]. The Forth expression size is evaluated during declaration, it must have the stack effect ( -- +n ), giving the size in bytes. The square bracket [ is part of the defined name.

Local data structures are initialized by copying size bytes from an address passed on the stack; uninitialized local data structures (after | in the declaration) are not erased, they just contain whatever data there was on the locals stack before.


begin-structure test-struct
  field: a1
  field: a2

: test-local {: foo[ test-struct ] :}
    foo[ a1 !  foo[ a2 !
    foo[ test-struct dump ;

Gforth allows defining locals everywhere in a colon definition. This poses the following questions:

Next: Standard Forth locals, Previous: Locals, Up: Locals   [Contents][Index]