Character Input and Output |
The numbers on top of the stack can represent anything. The top number might be
how many blue whales are left on Earth or your weight in kilograms. It can also
be an ASCII character. Try entering the following:
A D V E R T I S E M E N T
72 EMIT 105 EMIT
You should see the word "Hi" appear before the OK. The 72 is an ASCII 'H' and
105 is an 'i'. EMIT takes the number on the stack and outputs it as a character.
If you want to find the ASCII value for any character, you can use the word
ASCII . Enter:
CHAR W .
CHAR % DUP . EMIT
CHAR A DUP .
32 + EMIT
There is an ASCII chart in the back of this manual for a complete character
list.
Notice that the word CHAR is a bit unusual because its input comes not from
the stack, but from the following text. In a stack diagram, we represent that by
putting the input in angle brackets, <input>. Here is the stack diagram for
CHAR.
CHAR ( <char> -- char , get ASCII value of a character )
Using EMIT to output character strings would be very tedious. Luckily there
is a better way. Enter:
: TOFU ." Yummy bean curd!" ;
TOFU
The word ." , pronounced "dot quote", will take everything up to the next
quotation mark and print it to the screen. Make sure you leave a space after the
first quotation mark. When you want to have text begin on a new line, you can
issue a carriage return using the word CR . Enter:
: SPROUTS ." Miniature vegetables." ;
: MENU
CR TOFU CR SPROUTS CR
;
MENU
You can emit a blank space with SPACE . A number of spaces can be output
with SPACES . Enter:
CR TOFU SPROUTS
CR TOFU SPACE SPROUTS
CR 10 SPACES TOFU CR 20 SPACES SPROUTS
For character input, Forth uses the word KEY which corresponds to the
word EMIT for output. KEY waits for the user to press a key then leaves its
value on the stack. Try the following.
: TESTKEY ( -- )
." Hit a key: " KEY CR
." That = " . CR
;
TESTKEY
[Note: On some computers, the input if buffered so you will need to hit the
ENTER key after typing your character.]
EMIT ( char -- , output character )
KEY ( -- char , input character )
SPACE ( -- , output a space )
SPACES ( n -- , output n spaces )
CHAR ( <char> -- char , convert to ASCII )
CR ( -- , start new line , carriage return )
." ( -- , output " delimited text )