Making your own words. 4tH 4tH Forth compiler
Advertentie
Advertentie
CHAPTER 7. 4TH FUNDAMENTALS n1 n2 -- n3
68
Meaning it takes number n1 and n2 from the stack, multiplies them and leaves the product
(number n3) on the stack. The rightmost number is always on top of the stack, which means it is the first number which will be taken from the stack. The word ’.’ is described like this: n --
Which means it takes a number from the stack and leaves nothing. Now we get to the most powerful feature of it all. Take this program:
2
3
*
.
( leaves a number on the stack)
( leaves a number on the stack on top of the 2)
( takes both from the stack and leaves the result)
( takes the result from the stack and displays it)
Note that all data between the words ’*’ and ’.’ is passed implicitly! Like putting LEGO stones on top of another. Isn’t it great?
7.5
Making your own words
Of course, every serious language has to have a capability to extend it. So has 4tH. The only thing you have to do is to determine what name you want to give it. Let’s say you want to make a word which multiplies two numbers and displays the result.
Well, that’s easy. We’ve already seen how you have to code it. The only words you need are ’*’ and ’.’. You can’t name it ’*’ because that name is already taken. You could name it ’multiply’, but is that a word you want to type in forever? No, far too long.
Let’s call it ’*.’. Is that a valid name? If you’ve programmed in other languages, you’ll probably say it isn’t. But it is! The only characters you can’t use in a name are whitespace characters (<CR>, <LF>, <space>, <TAB>). Note that 4tH is not case-sensitive!
So ’*.’ is okay. Now how do we turn it into a self-defined word. Just add a colon at the beginning and a semi-colon at the end:
: *. * . ;
That’s it. Your word is ready for use. So instead of:
2 3 * .
We can type:
: *. * . ;
2 3 *.
And we can use our ’*.’ over and over again. Hurray, you’ve just defined your first word in
4tH!
Downloaden
Advertentie