Data Structures
Forth does not natively support complex data types, but creating your own is a trivial process. In fact, Forth makes no distinction at all between an array, a buffer, or any other data structure. To Forth, it’s just a block of memory that has been allocated, and it is up to the programmer how that space is used.
The Forth word here points to the next available space in memory. As memory is allocated to variables or data structures, the address returned by here changes accordingly. You can see the current value of here by:
The Forth word here points to the next available space in memory. As memory is allocated to variables or data structures, the address returned by here changes accordingly. You can see the current value of here by:
here u.
You begin by creating a pointer to the beginning of your data structure in memory and then allocating a block to hold your data. create creates a pointer in the dictionary to a single location in memory and allot allocates additional memory. (create has already allocated the first byte.)
For example, to create a buffer that is 100 bytes long:
For example, to create a buffer that is 100 bytes long:
create myBuffer
99 allot
We can see the pointer allocated to myBuffer and that 100 bytes have been allotted:
myBuffer u. here u.
The here pointer is 100 bytes further along.
Typing myBuffer places the start address of the buffer (or array or data structure) on the top of the stack. To index into that buffer, just add an appropriate amount to the address and perform a fetch or store as appropriate. For example, to read the 7th element (6 locations further on) of myBuffer, and copy it to the 9th location (8 further locations):
Typing myBuffer places the start address of the buffer (or array or data structure) on the top of the stack. To index into that buffer, just add an appropriate amount to the address and perform a fetch or store as appropriate. For example, to read the 7th element (6 locations further on) of myBuffer, and copy it to the 9th location (8 further locations):
myBuffer 6 + c@
myBuffer 8 + c!
Multidimensional arrays work exactly the same way. A 20x5 two-dimensional array is just 100 linear elements. (When using allot, remember to subtract 1 since create has already allocated the first byte.) To create a such an array:
create myArray
20 5 * ( size of the array )
1- ( we already have element 0 allocated )
allot
To access an element at column 5, row 3:
3 20 * ( each row is 20 elements )
5 + ( now at 5,3 )
myArray + ( add to start address )