Next: , Previous: CREATE, Up: Defining Words


5.9.2 Variables

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. ANS 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”

2Variable       "name" –         double       “two-variable”

fvariable       "name" –         float       “f-variable”

The defining word User behaves in the same way as Variable. The difference is that it reserves space in user (data) space rather than normal data space. In a Forth system that has a multi-tasker, each task has its own set of user variables.

User       "name" –         gforth       “User”