CREATE
¶The simplest defining word is CREATE
, used like this:
CREATE new-word1
CREATE
is a parsing word, i.e., it takes an argument from the
input stream (new-word1
in our example). It generates a
dictionary entry for new-word1
. When new-word1
is
executed, all that it does is leave an address on the stack. The
address represents the value of the dictionary pointer (HERE
)
at the time that new-word1
was defined. Therefore,
CREATE
is a way of associating a name with the address of a
region of memory.
Create
( "name" – ) core “Create”
Note that Standard Forth guarantees only for create
that its
body is contiguous with the following dictionary allocations (e.g.,
allot
, see Dictionary allocation). Also, in Standard Forth
only create
d words can be modified with does>
(see User-defined Defining Words). And in Standard Forth
>body
can only be applied to create
d words.
By extending this example to reserve some memory in data space, we end up with something like a variable. Here are two different ways to do it:
CREATE new-word2 1 cells allot \ reserve 1 cell without initializing it CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
The variable can be examined and modified using @
(“fetch”) and
!
(“store”) like this:
new-word2 @ . \ get address, fetch from it and display 1234 new-word2 ! \ new value, get address, store to it
A similar mechanism can be used to create arrays. For example, an 80-character text buffer:
CREATE text-buf 80 allot \ uninitialized text-buf 0 + c@ \ the 1st character (offset 0) text-buf 3 + c@ \ the 4th character (offset 3)
You can build arbitrarily complex data structures by allocating appropriate areas of memory. For further discussions of this, and to learn about some Gforth tools that make it easier, See Structures.