광고
광고
CHAPTER 7. 4TH FUNDAMENTALS
7.19
Using booleans
74
Booleans are expressions or values that are either true or false. They are used to conditionally execute parts of your program. In 4tH a value is false when it is zero and true when it is non-zero. Most booleans come into existence when you do comparisons. This example will determine whether the value in variable ’VAR’ is greater than 5. Try to predict whether it will evaluate to true or false: variable var
4 var !
var @ 5 > .
No, it wasn’t! But hey, you can print booleans as numbers. Well, they are numbers. But with a special meaning as we will see in the next section.
7.20
IF-ELSE constructs
Like most other languages you can use IF-ELSE constructs. Let’s enhance our previous example: variable var
4 var !
var @ 5 > if ." Greater" cr else ." Less or equal" cr then
So now our program tells you when it’s greater and when not. Note that contrary to other languages the condition comes before the ’IF’ and ’THEN’ ends the IF-clause. In other words, whatever path the program takes, it always continues after the ’THEN’. A tip: think of ’THEN’ as ’ENDIF’..
7.21
FOR-NEXT constructs
4tH has FOR-NEXT constructs as well. The number of iterations is known in this construct.
E.g. let’s print the numbers from 1 to 10:
11 1 do i . cr loop
The first number represents the limit. When the limit is reached or exceeded the loop terminates. The second number presents the initial value of the index. That’s where it starts off. So remember, this loop iterates at least once! You can use ’?DO’ instead of
’DO’. That will not enter the loop if the limit and the index are the same to begin with:
0 0 ?do i . cr loop
’i’ represents the index. It is not a variable or a constant, it is a predefined word, which puts the index on the stack, so ’.’ can get it from the stack and print it.
But what if I want to increase the index by two? Or want to count downwards? Is that possible. Sure. There is another construct to do just that. Okay, let’s take the first question:
다운로드
광고