home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / programming / a293_1 / !AForth_Examples_Defer < prev    next >
Encoding:
Text File  |  1999-04-27  |  1.3 KB  |  51 lines

  1. \ Forth source file
  2. \ Copyright Mads Meisner-Jensen, 6 Apr 1993
  3. \ Example showing how to implement DEFERred words
  4.  
  5. \ The default action of a word defined by DEFER is to issue an error message
  6. : (defer-error)  ( -- )
  7.   -1 ABORT" DEFERred word not initialised" ;
  8.  
  9. \ DEFER is a defining word.
  10. : DEFER  ( "name" -- )
  11.   CREATE  ['] (defer-error) ,  DOES> @ EXECUTE ;
  12.  
  13. \ Execution semantics of IS
  14. : (IS)  ( w1 w2 -- )
  15.   >BODY ! ;
  16.  
  17. \ IS assigns "name" to execute the word represented by the execution token w.
  18. \ IS is statesmart, meaning it can both be used inside and outside of a
  19. \ definition.
  20. : IS  ( w "name" -- )  \ Compilation: ( "name" -- )
  21.   BL WORD COUNT  ( c-addr u )  \ parse name delimited by space
  22.   FORTH-WORDLIST SEARCH-WORDLIST  \ get its execution token
  23.   IF  \ ..found
  24.     STATE @ IF  \ compiling..
  25.       POSTPONE LITERAL  \ compile execution semantics of IS..
  26.       ['] (IS) COMPILE,
  27.     ELSE  \ interpreting
  28.       (IS)
  29.     THEN
  30.   ELSE
  31.     -1 ABORT" DEFERred Word not found"
  32.   THEN
  33. ; IMMEDIATE
  34.  
  35.  
  36.  
  37. \ Example of usage ____________________________________________________________
  38.  
  39. \ Try typing G1 followed by GREET at the Forth prompt
  40. \ Then see what happens when you afterwards type G2 followed by GREET.
  41.  
  42. DEFER GREET
  43.  
  44. : HELLO  ( -- )  ." Hello world." ;
  45. : HI  ( -- )  ." Hi there." ;
  46.  
  47. : G1
  48.   ['] HELLO IS GREET ;
  49. : G2
  50.   ['] HI IS GREET ;
  51.