Character I/O

Because Forth is not a typed language, 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 might also be an ASCII character. Try entering the following:

72 emit 105 emit

You should see the word "Hi" appear. 72 is an ASCII H and 105 is an i. The word emit takes a number on the stack and outputs it as a character. To get the ASCII value of a character, prepend the character with a single-quote. Enter:

'W .
'% dup . emit
'A dup .
32 + emit

The use of the single-quote character is a bit unusual. It tells the RetroForth interpreter that the character that follows should be converted to the ASCII code representing it, rather than being considered a word. There are other such modifiers in RetroForth which can make inputting numbers simpler:

'a | Gives 97, the ASCII value of 'a'
%1100 | Gives 12, or 1100 binary
$ff | 255, or hexadecimal FF
&010 | 8, or octal 10
#123 | 123 - decimal 123

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. In other Forths one may output more than one space with the word spaces. Let's write one for RetroForth:

: spaces repeat space until ;
TOFU SPROUTS
TOFU space SPROUTS
cr 10 spaces TOFU cr 20 spaces SPROUTS

Notice that the new word we created, spaces, uses a loop construct. The word repeat starts a series of words which will be run repeatedly. The word until subtracts one from TOS; if it's not zero then it jumps back to just after the repeat. We'll see more of these kinds of words later on.

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
." The ASCII value = " . cr
;
TESTKEY

Note: On some computers, the input if buffered so you will need to hit the ENTER key after typing your character.