Making decisions
IF
A block IF has no THEN. It ends with END IF.
hp = 35
IF hp > 50
PRINT "fine"
ELSE IF hp > 0
PRINT "hurt"
ELSE
PRINT "down"
END IF
hurt
THEN is for when the whole thing fits on one line. That form has no END,
and it can have an ELSE on the end — even ELSE IF, if you can stand the
length.
hp = 0
IF hp = 0 THEN PRINT "game over"
IF hp > 0 THEN PRINT "you won't see this"
IF hp > 50 THEN PRINT "fine" ELSE PRINT "not fine"
IF hp > 50 THEN mood = "happy" ELSE IF hp > 0 THEN mood = "worried" ELSE mood = "napping"
PRINT mood
game over
not fine
napping
Each side takes one statement. When you need two, that’s what the block form is for.
From BASIC: A block
IFdoesn’t end its first line withTHEN, and it’sELSE IF, two words. (If you’ve got a lot of old code, the last lesson shows a way to let me read it as it is.)
From Python:
ELSE IFis yourelif. No colons.
From JavaScript: No parentheses needed around the condition, and no braces around the block.
From Lua:
ELSE IFis yourelseif, and there’s nothenon a block.
SELECT CASE
When you’re asking what one value is, SELECT CASE reads better than a
ladder of ELSE IF. I work the value out once, then run the lines under the
first CASE that fits — only that one.
score = 95
SELECT CASE score
CASE 100
PRINT "perfect!"
CASE 90 TO 99
PRINT "great"
CASE 50, 60, 70, 80
PRINT "a round number"
CASE IS < 50
PRINT "oops"
CASE ELSE
PRINT "fine"
END SELECT
great
A CASE can list values with commas, give a range with TO, or compare with
IS. CASE ELSE catches everything and goes last. Change score over there
and see which one I pick.
From Python: This is your
match, for values.
From JavaScript: This is your
switch, without thebreak. A case never falls through into the next.
From Lua: You never had one of these. Enjoy!