The previous section showed how a sequence of commands could be used to generate a variable. As a final refinement, the whole code sequence can be wrapped up in a defining word (pre-empting the subject of the next section), making it easier to create new variables:
: myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ; : myvariable0 ( "name" -- a-addr ) CREATE 0 , ; myvariableX foo \ variable foo starts off with an unknown value myvariable0 joe \ whilst joe is initialised to 0 45 3 * foo ! \ set foo to 135 1234 joe ! \ set joe to 1234 3 joe +! \ increment joe by 3.. to 1237
Not surprisingly, there is no need to define myvariable
, since
Forth already has a definition Variable
. Standard Forth does not
guarantee that a Variable
is initialised when it is created
(i.e., it may behave like myvariableX
). In contrast, Gforth’s
Variable
initialises the variable to 0 (i.e., it behaves exactly
like myvariable0
). Forth also provides 2Variable
and
fvariable
for double and floating-point variables, respectively
– they are initialised to 0. and 0e in Gforth. If you use a Variable
to
store a boolean, you can use on
and off
to toggle its
state.
Variable
( "name" – ) core “Variable”
Define name and reserve a cell starting at addr.
name run-time: ( -- addr )
.
AVariable
( "name" – ) gforth-0.2 “AVariable”
Works like variable
, but (when used in cross-compiled
code) tells the cross-compiler that the cell stored in the
variable is an address.
2Variable
( "name" – ) double “two-variable”
fvariable
( "name" – ) floating “f-variable”
Finally, for buffers of arbitrary length there is
buffer:
( u "name" – ) core-ext “buffer-colon”
Define name and reserve u bytes starting at addr.
name run-time: ( -- addr )
. Gforth initializes the
reserved bytes to 0, but the standard does not guarantee this.