www.delorie.com/gnu/docs/gforth/gforth_97.html   search  
 
Buy GNU books!


Gforth Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.9.1 CREATE

Defining words are used to create new entries in the dictionary. The simplest defining word is CREATE. CREATE is 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 data space 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.

doc-create

Note that in ANS Forth guarantees only for create that its body is in dictionary data space (i.e., where here, allot etc. work, see section 5.7.2 Dictionary allocation). Also, in ANS Forth only created words can be modified with does> (see section 5.9.8 User-defined Defining Words). And in ANS Forth >body can only be applied to created 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 - initial value undefined
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 input buffer:

 
CREATE text-buf 80 chars allot

text-buf 0 chars c@ \ the 1st character (offset 0)
text-buf 3 chars 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 section 5.20 Structures.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003