Lua If
An if statement runs a block of code only when its condition is true. A condition is a check that gives true or false.
A true condition runs the block
The score reaches the pass mark, so the condition is true. The message inside the block prints.
local score = 80
if score >= 50 then
print("You passed")
endA false condition skips the block
The score is below the pass mark this time, so the block is skipped. Only the two marker lines around it print.
print("Start")
local score = 30
if score >= 50 then
print("You passed")
end
print("Done")The condition can be built in the if line
The comparison sits directly in the if line instead of being stored first. The age reaches 18, so the block runs.
local age = 18
if age >= 18 then
print("Adult ticket")
endExample
local age = 16
print("Welcome")
if age >= 12 then
print("Teen ticket allowed")
end
print("Enjoy the film")Key points
- Shape: an if statement starts with the word if, then the condition, then the word then.
- Block: the lines between then and end form the block that may run.
- End: the word end closes the if statement.
- True runs: the block runs when the condition gives true.
- False skips: the block is skipped when the condition gives false, and nothing extra is printed.
- Indent: lines inside the block are usually indented, to show they belong to the if statement.
In this example, the first line prints a greeting that always appears. The if statement then checks whether the age of 16 reaches 12, and it does, so the teen ticket line prints. The last line sits outside the block, so it prints as well.
Note
Lua uses the words then and end where some other languages use curly braces.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line correctly starts an if statement in Lua?