If Statement
Up to now, every line of your programs ran, from top to bottom. The if statement changes that. It runs a block of code only when a condition is true.
local age = 20
if age >= 18 then
print("You can vote")
end
print("Done")
Output:
You can vote
Done
The shape is if condition then ... end. The lines between then and end are the block. They run only when the condition is true. Here age >= 18 is true, so the block runs.
Lua does not need parentheses around the condition or curly braces around the block. The keywords then and end mark where the block starts and stops.
Now change age to 16:
local age = 16
if age >= 18 then
print("You can vote")
end
print("Done")
Output:
Done
The condition is false, so Lua skips the block. The print("Done") after end is outside the if, so it runs in both cases.
age >= 18 ?
/ \
true false
| |
"You can vote" |
\ /
"Done" (always)
Adding else
Add else when you want something to happen when the condition is false:
local age = 16
if age >= 18 then
print("You can vote")
else
print("Not yet")
end
Output:
Not yet
Exactly one of the two blocks runs. One end closes the whole statement, and else does not need its own then.
Two reminders
The condition can be any value, not only a comparison. Remember the rule from the Booleans and Nil lesson: only false and nil count as false. 0 and "" count as true.
"Not equal" is written ~= in Lua. To check that an answer is not "quit", you write if answer ~= "quit" then.
Indent the lines inside a block. Lua does not need the spaces, but they show the reader which lines belong to the if.
In the exercise, print a warning line only when the temperature is above 30.