If and else
Lesson 4.1
An if statement runs code only when a condition is true. With elseif and else it chooses between several paths.
if
local health = 4
if health < 6 then
print("You are low on health!")
end
The shape is always if condition then ... end. The code between then and end runs only when the condition is truthy. Indent it by two or four spaces so you can see where the block starts and stops. Lua doesn’t care about the indentation, but readers do.
else
else gives the other path:
local is_day = false
if is_day then
print("The sun is up.")
else
print("Watch out for mobs.")
end
elseif
For more than two choices, chain them with elseif. Lua checks the conditions from the top and runs the first one that is true. The rest are skipped:
local light = 9
if light == 0 then
print("pitch black")
elseif light < 8 then
print("dark: mobs can spawn")
elseif light < 15 then
print("lit")
else
print("full light")
end
This prints lit. elseif is one word. Writing else if starts a new if inside the else, which needs its own end.
Conditions can be any value
Remember the rule from the last lesson: only false and nil are falsy. So you can test whether something exists simply by naming it:
local held_item = "Torch"
if held_item then
print("Holding " .. held_item) --> Holding Torch
end
Nesting
An if can sit inside another if:
local mob = "Creeper"
local distance = 2
if mob == "Creeper" then
if distance < 3 then
print("Run!")
else
print("Keep an eye on it.")
end
end
Deep nesting gets hard to read. Often you can join the conditions with and, or use an early return inside a function (you will see this in the functions chapter).
Comparing against many values
Lua has no switch statement. Use an elseif chain, or, when you only map values to values, a table lookup (tables come later, in Dictionaries):
local damage = { wooden = 4, stone = 5, iron = 6, diamond = 7 }
print(damage["iron"]) --> 6
Try it
Write code that takes a local time = 13000 (Minecraft ticks, 0 to 23999) and prints which part of the day it is: day for 0 to 11999, sunset for 12000 to 12999, night for 13000 to 22999, and sunrise for the rest. Test it with a few values.
Show a solution
local time = 13000
if time < 12000 then
print("day")
elseif time < 13000 then
print("sunset")
elseif time < 23000 then
print("night")
else
print("sunrise")
end
--> night
Because each branch is only checked when the earlier ones failed, you don’t need to write time >= 12000 and time < 13000.
Recap: if ... then ... elseif ... else ... end runs the first branch whose condition is truthy.