Using the then keyword

The examples so far have shown how to use the if keyword to test a condition and then execute code, followed by the endif keyword. This approach is necessary when you need to add multiple statements within an if statement. However, there will be occasions when only one statement is required for an if statement. When this is the case the then keyword can be used to follow the expression, allowing you to add a statement immediately after the then keyword, eliminating the need for the endif keyword, as shown in this example.

score as integer = 100

do if score = 100 then print ( "the score is 100" )
sync ( ) loop

The above code is effectively the same as this.

score as integer = 100

do if score = 100 print ( "the score is 100" ) endif
sync ( ) loop

The key difference is that when using the first method the only code associated with the if statement is that which follows the then keyword and it must be on the same line. Whereas the second method lets you add multiple statements between it and the endif keyword.

Using the then keyword is a good option when you only require one statement to be executed if the condition for the if statement is true.

To demonstrate both approaches a simple example has been created.

score as integer = 0

do if score >= 100 then print ( "the score is 100" )
if score < 100 score = score + 1 print ( "the score is less than 100" ) endif
print ( score )
sync ( ) loop

The first if statement checks if the score is greater than or equal to 100. If this is true then a call to print is made to display "the score is 100" on screen. As the then keyword has been used any statement after the expression and on the same line will be executed when the condition is true. When the program first runs the score is initially set to 0, so this condition will be false, at least to begin with.

The second if statement checks if the score is less than 100 and because we're not using the then keyword we can perform multiple actions on new lines beneath it, which in this case is to increment the score variable by 1 and then to call print in order to display "the score is less than 100" on screen. The final part is to add an endif to finish this block of code. Only the lines between the if and endif will be executed if the condition is true.

Finally a call is made to display the score on screen (print) along with another call to update the screen (sync).

Run the program and watch what happens as the score variable gets larger. Initially only the second if statement's condition is true, so the score gets 1 added to it each time, however, after a short period the score ends up being greater than or equal to 100, so the first if statement's condition becomes true, while the second if statement's condition becomes false.