Control Flow in Lua

Control flow statements allow your programs to make decisions and execute different code paths based on conditions. Lua provides if, elseif, and else statements for conditional logic.

The if Statement

The basic conditional statement executes code only when a condition is true:

local age = 18

if age >= 18 then
    print("You are eligible to vote!")
end

-- Multiple conditions
local temperature = 25
if temperature > 30 then
    print("It's hot outside!")
end

if-else Statement

The else clause provides alternative code when the condition is false:

local score = 85

if score >= 60 then
    print("You passed!")
else
    print("You failed!")
end

-- Practical example
local is_logged_in = false
if is_logged_in then
    print("Welcome back!")
else
    print("Please log in to continue.")
end

if-elseif-else Chain

For multiple conditions, use elseif:

local grade = 85

if grade >= 90 then
    print("Grade: A")
elseif grade >= 80 then
    print("Grade: B")
elseif grade >= 70 then
    print("Grade: C")
elseif grade >= 60 then
    print("Grade: D")
else
    print("Grade: F")
end

Nested if Statements

You can nest if statements inside other if statements:

local age = 25
local has_license = true

if age >= 18 then
    if has_license then
        print("You can drive!")
    else
        print("You need to get a license first.")
    end
else
    print("You're too young to drive.")
end

Logical Conditions

Combine conditions with logical operators:

local age = 22
local has_ticket = true
local is_student = false

-- AND condition
if age >= 18 and has_ticket then
    print("Entry granted!")
end

-- OR condition
if is_student or age < 18 then
    print("Discount available!")
end

-- Complex condition
if age >= 18 and has_ticket and not is_student then
    print("Full price adult ticket.")
end

Truthy and Falsy Values

In Lua, only nil and false are falsy. Everything else is truthy:

local value1 = 0        -- truthy (zero is truthy)
local value2 = ""       -- truthy (empty string is truthy)
local value3 = {}       -- truthy (empty table is truthy)
local value4 = nil      -- falsy
local value5 = false    -- falsy

if value1 then
    print("Zero is truthy")  -- This will print
end

if value4 then
    print("This won't print")  -- This won't execute
end

Practical Examples

User Authentication

local username = "alice"
local password = "secret123"
local is_active = true

if username and password then
    if is_active then
        if username == "admin" then
            print("Welcome, Administrator!")
        else
            print("Welcome, User!")
        end
    else
        print("Account is deactivated.")
    end
else
    print("Invalid credentials.")
end

Temperature Checker

local temperature = 22

if temperature > 30 then
    print("Very hot! Stay hydrated.")
elseif temperature > 20 then
    print("Perfect weather!")
elseif temperature > 10 then
    print("Cool weather. Bring a jacket.")
else
    print("Cold! Dress warmly.")
end

Input Validation

local email = "[email protected]"
local age = 25

if email and age then
    if string.find(email, "@") and age > 0 then
        print("Valid input provided.")
    else
        print("Invalid email or age.")
    end
else
    print("Please provide both email and age.")
end

Common Patterns

Default Values

local name = nil
local display_name = name or "Guest"
print(display_name)  -- Guest

Range Checking

local score = 75

if score >= 0 and score <= 100 then
    print("Valid score range.")
else
    print("Invalid score. Must be between 0 and 100.")
end

Multiple Condition Testing

local day = "Monday"

if day == "Saturday" or day == "Sunday" then
    print("It's the weekend!")
else
    print("It's a weekday.")
end

Best Practices

  1. Keep conditions simple and readable
  2. Use meaningful variable names in conditions
  3. Handle edge cases like nil values
  4. Use logical operators to combine related conditions
  5. Consider using early returns in functions for complex logic

Next Steps

Now that you understand control flow, learn about loops to repeat code efficiently.

For more control flow details, see the Lua manual.

Last updated on