home *** CD-ROM | disk | FTP | other *** search
- \ Forth source file
- \ Copyright Mads Meisner-Jensen, 6 Apr 1993
- \ Examples of data structures
-
- \ Array words _________________________________________________________________
-
- \ Dumb array of u chars.
- \ Compilation: ( u "name" -- )
- : ARRAY ( -- a-addr ) CREATE CHARS ALLOT ALIGN ;
-
- \ Array of u cells.
- \ Compilation: ( u "name" -- )
- : 1ARRAY ( i -- a-addr )
- CREATE CELLS ALLOT DOES> SWAP CELLS + ;
-
- \ Double cell array of u double cells.
- \ Compilation: ( u "name" -- )
- : 2ARRAY ( i -- a-addr )
- CREATE 2* CELLS ALLOT DOES> SWAP 2* CELLS + ;
-
- \ String array of u1 strings, each of u2 chars. First string is aligned.
- \ Compilation: ( u1 u2 "name" -- )
- : $ARRAY ( i -- c-addr )
- CREATE DUP , * CHARS ALLOT ALIGN DOES> SWAP OVER @ * CHARS + CELL+ ;
-
-
- \ Record data structure handling (called 'struct' in C) _______________________
-
- \ Defining word, which creates RECORD: as another defining word.
- : RECORD: ( "name" -- sys )
- CREATE HERE 0 , 0
- DOES> POSTPONE CREATE @ ALLOT DOES> + ;
- : MEMBER ( sys -- sys ) OVER CONSTANT + ALIGNED ;
- : ;RECORD ( sys -- ) SWAP ! ;
-
-
- \ Example of usage of RECORD words
-
- RECORD: CUSTOMER \ define a new record type called CUSTOMER
- 20 CHARS MEMBER NAME \ specify size and name of each member of the record
- 1 CELLS MEMBER CASH
- 1 CELLS MEMBER ID
- ;RECORD
-
- \ Define word to display contents of a record
- : CUSTOMER. ( a-addr -- )
- CR ." Name = " DUP NAME + COUNT TYPE
- CR ." Cash = " DUP CASH + @ .
- CR ." Id = " ID + @ .
- ;
-
- CUSTOMER SMITH \ make an instantiation of CUSTOMER called SMITH
- CUSTOMER JONES \ ditto JONES
-
- : TEST-RECORD ( -- )
- S" Nick Smith" \ intialise name of SMITH record
- NAME SMITH 2DUP C!
- CHAR+ SWAP MOVE
- 22381 CASH SMITH ! \ initialise CASH field of SMITH record
- 19660412 ID SMITH ! \ initialise ID field of SMITH record
- S" Jim Jones"
- NAME JONES 2DUP C! CHAR+ SWAP MOVE
- -2347 CASH JONES !
- 18990101 ID JONES !
- 0 SMITH CUSTOMER. \ note the zero preceding the record name, when it
- 0 JONES CUSTOMER. \ is to be printed.
- ;
-