home *** CD-ROM | disk | FTP | other *** search
- \ Forth source file
- \ Copyright Mads Meisner-Jensen, 6 Apr 1993
- \ Examples of basic principles, syntax etc.
-
- \ The backslash character at the start of this line is one of the
- \ comment characters. It causes Forth to ignore the rest of the current line.
-
- ( This is another comment. It is terminated by a right parenthesis: )
-
- \ Observe the trailing space after the left paranthesis and the backslash
- \ The space has to be there because the comment characters are actually just
- \ Forth words.
-
-
-
- \ Count from zero to 999 displaying the numbers.
- : THOUSAND ( -- ) \ The stack diagram shows no input nor output
- 1000 0 DO \ loop limit and start value
- I . \ get loop index and print it in free field format
- LOOP \ loop back
- ; \ terminate the definition
-
- \ Input a string from the keyboard and display it afterwards
- : INPUT ( -- )
- HERE \ used as temporary buffer
- 80 \ maximum number of characters to accept
- CR ." Input string:" \ type a prompt
- ACCEPT ( +n ) \ recieve input from the keyboard
- HERE SWAP ( c-addr u )
- CR TYPE \ new-line and display the string
- ;
-
- \ Count to 99 using a WHILE construct
- : HUNDRED ( -- )
- 0 \ initialise counter
- BEGIN \ mark beginning of loop
- DUP 100 <
- WHILE \ while less than hundred do...
- 1+ DUP . \ increment and print the counter
- REPEAT \ end of loop
- ;
-
- \ Test if char is a digit
- : DIGIT? ( char -- flag )
- [CHAR] 0 [ CHAR 9 1+ ] LITERAL ( char "0" "9"+1 )
- WITHIN ( flag )
- ;
-
- \ Input a positive number, allowing only digits to be typed.
- : N-INPUT ( -- ud )
- 0 \ length of string input so far
- BEGIN
- KEY DUP 13 = INVERT
- WHILE \ while not <RET>
- DUP DIGIT? IF \ was it a digit?
- 2DUP ( char u char u )
- HERE + C! \ store ascii digit
- 1+ SWAP ( u+1 char )
- EMIT \ emit char
- ELSE
- DROP ( char -- )
- THEN
- REPEAT \ loop back for more digits
- DROP ( u char -- u )
- >R 0 S>D HERE R> ( ud c-addr u )
- >NUMBER 2DROP ( ud )
- ;
-
- \ Return value of RISC-OS centisecond counter
- : MONOTIME ( -- u )
- [ 0 1 ] \ specify no input registers and one (R0) output register
- SYS OS_ReadMonotonicTime
- ;
-
-
- \ Alas, no more examples...
-