Lua - If/Else
Overview
Estimated time: 20–25 minutes
Conditional statements allow your program to make decisions and execute different code paths based on conditions. This tutorial covers if, elseif, and else statements with practical examples.
Learning Objectives
- Master basic if statements and conditions
- Use elseif for multiple conditions
- Implement else clauses for default cases
- Create nested conditional statements
- Apply best practices for conditional logic
Prerequisites
- Understanding of Lua operators (especially relational and logical)
- Knowledge of boolean values and truthiness
Basic If Statement
The simplest form of conditional statement:
local age = 18
if age >= 18 then
print("You are an adult")
end
print("Program continues...")
-- Another example
local temperature = 25
if temperature > 30 then
print("It's hot outside!")
end
if temperature < 10 then
print("It's cold outside!")
end
Expected Output:
You are an adult
Program continues...
If-Else Statement
Provide an alternative action when the condition is false:
local score = 75
if score >= 60 then
print("You passed!")
else
print("You failed!")
end
-- Voting eligibility
local age = 16
if age >= 18 then
print("You can vote")
else
print("You cannot vote yet. You need to wait " .. (18 - age) .. " more years.")
end
-- Weather advice
local is_raining = true
if is_raining then
print("Take an umbrella!")
else
print("Enjoy the sunshine!")
end
Expected Output:
You passed!
You cannot vote yet. You need to wait 2 more years.
Take an umbrella!
If-Elseif-Else Chain
Handle multiple conditions with elseif:
local grade = 85
if grade >= 90 then
print("Grade: A (Excellent!)")
elseif grade >= 80 then
print("Grade: B (Good job!)")
elseif grade >= 70 then
print("Grade: C (Satisfactory)")
elseif grade >= 60 then
print("Grade: D (Needs improvement)")
else
print("Grade: F (Failed)")
end
-- Day of the week
local day = 3
if day == 1 then
print("Monday - Start of the work week")
elseif day == 2 then
print("Tuesday - Getting into the groove")
elseif day == 3 then
print("Wednesday - Hump day!")
elseif day == 4 then
print("Thursday - Almost there")
elseif day == 5 then
print("Friday - TGIF!")
elseif day == 6 or day == 7 then
print("Weekend - Time to relax!")
else
print("Invalid day number")
end
Expected Output:
Grade: B (Good job!)
Wednesday - Hump day!
Complex Conditions
Use logical operators to create complex conditions:
local age = 25
local has_license = true
local has_car = false
-- Multiple conditions with AND
if age >= 18 and has_license then
print("You can legally drive")
if has_car then
print("You can drive your own car")
else
print("You need to borrow or rent a car")
end
else
print("You cannot drive legally")
end
-- Multiple conditions with OR
local is_weekend = true
local is_holiday = false
if is_weekend or is_holiday then
print("No work today!")
else
print("Time to go to work")
end
-- Complex condition
local temperature = 22
local is_sunny = true
local wind_speed = 5
if temperature >= 20 and temperature <= 30 and is_sunny and wind_speed < 10 then
print("Perfect day for a picnic!")
else
print("Maybe stay indoors today")
end
Expected Output:
You can legally drive
You need to borrow or rent a car
No work today!
Perfect day for a picnic!
Nested If Statements
Place if statements inside other if statements:
local user_type = "premium"
local account_active = true
local balance = 150
if account_active then
print("Account is active")
if user_type == "premium" then
print("Premium user detected")
if balance >= 100 then
print("Sufficient balance for premium features")
print("Access granted to all features")
else
print("Low balance - some features may be restricted")
end
elseif user_type == "standard" then
print("Standard user")
if balance >= 50 then
print("Access granted to standard features")
else
print("Please add funds to your account")
end
else
print("Unknown user type")
end
else
print("Account is inactive - please contact support")
end
Expected Output:
Account is active
Premium user detected
Sufficient balance for premium features
Access granted to all features
Truthiness in Conditions
Remember: only nil
and false
are falsy in Lua:
-- Testing various values
local values = {true, false, nil, 0, "", "hello", {}, -1}
for i, value in ipairs(values) do
if value then
print("Value " .. i .. " (" .. tostring(value) .. ") is truthy")
else
print("Value " .. i .. " (" .. tostring(value) .. ") is falsy")
end
end
-- Practical example: checking if a table has elements
local fruits = {"apple", "banana"}
local empty_fruits = {}
if #fruits > 0 then
print("We have fruits:", fruits[1])
else
print("No fruits available")
end
if #empty_fruits > 0 then
print("We have fruits in empty_fruits")
else
print("empty_fruits is empty")
end
Expected Output:
Value 1 (true) is truthy
Value 2 (false) is falsy
Value 3 (nil) is falsy
We have fruits: apple
empty_fruits is empty
Practical Examples
User Authentication System
local function authenticate_user(username, password, is_admin)
if not username or username == "" then
return "Error: Username is required"
end
if not password or password == "" then
return "Error: Password is required"
end
if #password < 8 then
return "Error: Password must be at least 8 characters"
end
-- Simulate authentication
if username == "admin" and password == "admin123" then
if is_admin then
return "Welcome, Administrator!"
else
return "Welcome, " .. username .. "!"
end
elseif username == "user" and password == "password123" then
return "Welcome, " .. username .. "!"
else
return "Error: Invalid credentials"
end
end
-- Test the authentication
print(authenticate_user("", "password123", false))
print(authenticate_user("user", "123", false))
print(authenticate_user("user", "password123", false))
print(authenticate_user("admin", "admin123", true))
Temperature Converter
local function convert_temperature(temp, from_unit, to_unit)
if not temp or not from_unit or not to_unit then
return "Error: Missing parameters"
end
-- Normalize units to lowercase
from_unit = string.lower(from_unit)
to_unit = string.lower(to_unit)
local celsius
-- Convert to Celsius first
if from_unit == "celsius" or from_unit == "c" then
celsius = temp
elseif from_unit == "fahrenheit" or from_unit == "f" then
celsius = (temp - 32) * 5 / 9
elseif from_unit == "kelvin" or from_unit == "k" then
celsius = temp - 273.15
else
return "Error: Unknown source unit"
end
-- Convert from Celsius to target unit
if to_unit == "celsius" or to_unit == "c" then
return celsius
elseif to_unit == "fahrenheit" or to_unit == "f" then
return celsius * 9 / 5 + 32
elseif to_unit == "kelvin" or to_unit == "k" then
return celsius + 273.15
else
return "Error: Unknown target unit"
end
end
-- Test conversions
print("32°F to Celsius:", convert_temperature(32, "f", "c"))
print("0°C to Fahrenheit:", convert_temperature(0, "c", "f"))
print("273.15K to Celsius:", convert_temperature(273.15, "k", "c"))
print("Invalid conversion:", convert_temperature(100, "x", "c"))
Game Logic Example
local function check_game_status(player_health, enemy_health, player_level, has_special_item)
if player_health <= 0 then
return "Game Over - You died!"
end
if enemy_health <= 0 then
return "Victory - Enemy defeated!"
end
if player_health < 20 then
if has_special_item then
return "Low health - Use your special item!"
else
return "Critical health - Find a health potion!"
end
end
if enemy_health < 30 and player_level >= 5 then
return "Enemy is weak - Use your special attack!"
end
if player_health > 80 and enemy_health > 80 then
return "Both fighters are strong - This will be a long battle!"
end
return "Battle continues..."
end
-- Test game scenarios
print(check_game_status(0, 50, 3, false))
print(check_game_status(100, 0, 5, true))
print(check_game_status(15, 60, 2, true))
print(check_game_status(85, 25, 6, false))
Expected Output:
Error: Username is required
Error: Password must be at least 8 characters
Welcome, user!
Welcome, Administrator!
32°F to Celsius: 0
0°C to Fahrenheit: 32
273.15K to Celsius: 0
Invalid conversion: Error: Unknown source unit
Game Over - You died!
Victory - Enemy defeated!
Low health - Use your special item!
Enemy is weak - Use your special attack!
Common Pitfalls
- Missing
then
: Always includethen
after the condition - Assignment vs comparison: Use
==
for comparison, not=
- Truthiness confusion: Remember that
0
and""
are truthy in Lua - Missing
end
: Eachif
must have a correspondingend
- Complex conditions: Use parentheses to make complex conditions clearer
Checks for Understanding
- What keyword is required after an if condition?
- How do you check if a number is between 10 and 20 (inclusive)?
- What values are considered falsy in Lua?
- What's the difference between
if
andelseif
? - How do you end an if statement?
Show answers
then
- required after every if/elseif conditionif number >= 10 and number <= 20 then
- Only
nil
andfalse
are falsy; everything else is truthy if
starts a new conditional block;elseif
adds additional conditions to the same block- With the
end
keyword
Next Steps
Now that you can make decisions in your programs, you're ready to learn about loops, which allow you to repeat code blocks multiple times.