IF statements
IF statements allow your program to perform different actions depending on a condition. The condition can be any expression with a boolean type (TRUE or FALSE).
IF THEN
In the example below, the condition we test is AGE < 8. If that is TRUE, then we print a warning message. Otherwise the code between THEN and END IF is skipped.
MODULE MAIN
FUNC SHOW_NOTICE(AGE: INT): INT
IF AGE < 8 THEN
# THIS CODE ONLY RUNS WHEN AGE IS LESS THAN 8
CONSOLE::PRINT("YOU ARE TOO YOUNG TO RIDE.")
END IF
# THIS CODE ALWAYS RUNS
CONSOLE::PRINT("{N}")
END FUNC
FUNC START()
CONSOLE::INIT()
SHOW_NOTICE(5)
END FUNC
END MODULE
ELSE
Instead of skipping to END IF, we can instead use ELSE to provide an alternative behavior:
MODULE MAIN
FUNC SHOW_NOTICE(AGE: INT): INT
IF AGE < 8 THEN
# ONLY RUNS WHEN AGE < 8
CONSOLE::PRINT("YOU ARE TOO YOUNG TO RIDE.")
ELSE
# ONLY RUNS WHEN AGE >= 8
CONSOLE::PRINT("YOU ARE OLD ENOUGH TO RIDE.")
END IF
# THIS CODE ALWAYS RUNS
CONSOLE::PRINT("{N}")
END FUNC
FUNC START()
CONSOLE::INIT()
SHOW_NOTICE(5)
END FUNC
END MODULE
ELSIF
We can use ELSIF to consider multiple conditions:
MODULE MAIN
FUNC SHOW_NOTICE(AGE: INT): INT
IF AGE < 8 THEN
# LESS THAN 8
CONSOLE::PRINT("YOU ARE TOO YOUNG TO RIDE.")
ELSIF AGE <= 12 THEN
# BETWEEN 8 AND 12
CONSOLE::PRINT("ASK YOUR PARENT FOR PERMISSION.")
ELSIF AGE >= 18 THEN
# 18 OR OLDER
CONSOLE::PRINT("YOU ARE TOO OLD TO RIDE.")
ELSE
# BETWEEN 13 AND 17
CONSOLE::PRINT("YOU ARE OLD ENOUGH TO RIDE.")
END IF
# THIS CODE ALWAYS RUNS
CONSOLE::PRINT("{N}")
END FUNC
FUNC START()
CONSOLE::INIT()
SHOW_NOTICE(5)
END FUNC
END MODULE
You may wonder why we need ELSIF. Couldn't we just use ELSE and IF?
You can, but the END IF indentation will accumulate quickly:
. . .
IF AGE < 8 THEN
# LESS THAN 8
CONSOLE::PRINT("YOU ARE TOO YOUNG TO RIDE.")
ELSE
IF AGE <= 12 THEN
# BETWEEN 8 AND 12
CONSOLE::PRINT("ASK YOUR PARENT FOR PERMISSION.")
ELSE
IF AGE >= 18 THEN
# 18 OR OLDER
CONSOLE::PRINT("YOU ARE TOO OLD TO RIDE.")
ELSE
# BETWEEN 13 AND 17
CONSOLE::PRINT("YOU ARE OLD ENOUGH TO RIDE.")
END IF
END IF
END IF
. . .
ELSIF is cleaner and simpler. (Of course ELSIF could be spelled out as ELSE IF, but then beginners might have trouble recognizing which IF matches the END IF.)
DO
Programs frequently use very simple IF statements, for example:
. . .
IF COUNT < 0 THEN
0 -> COUNT
END IF
. . .
. . .
IF COUNT > 10 THEN
RETURN RESULT
END IF
. . .
You can save a line of code by using DO instead of THEN. The examples below have identical meaning as above:
. . .
IF COUNT < 0
DO 0 -> COUNT
. . .
. . .
IF COUNT > 10
DO RETURN RESULT
. . .
DO can only be used with simple statements such as assignments or function calls. The following examples are NOT allowed:
. . .
# ⚠️ ERROR: "LOOP" IS NOT ALLOWED WITH "DO"
IF COUNT < 0
DO LOOP
END LOOP
. . .
. . .
# ⚠️ ERROR: "IF" IS NOT ALLOWED WITH "DO"
IF COUNT < 0
DO IF COUNT > 5
DO 0 -> COUNT
. . .