Home / Lessons / Lesson 7
Intermediate Free

Control Flow (If/Else)

Games are all about logic and rules. Control Flow allows your script to make decisions based on specific conditions.


The If Statement

An if statement checks if a condition is true. If it is, the code inside the block runs. If it's false, the code is skipped.

Basic Condition
local playerHealth = 50

if playerHealth < 100 then
    print("Player is injured!")
end

Else and ElseIf

What if you want to do something different when the condition is false? You use else. If you have multiple different conditions to check in a row, use elseif.

Multiple Conditions
local score = 85

if score >= 90 then
    print("Grade: A")
elseif score >= 80 then
    print("Grade: B")
else
    print("Grade: C or lower")
end

Logical Operators

You can combine multiple conditions using and, or, and not.

  • and: True only if BOTH sides are true.
  • or: True if AT LEAST ONE side is true.
  • not: Reverses the condition (true becomes false).

Guard Clauses (Pro Pattern)

Beginners often write heavily nested if statements, pushing their code far to the right. Professional developers use Guard Clauses. A guard clause checks for a bad condition immediately and returns (stops the function), keeping the rest of the code clean and un-nested.

Using Guard Clauses
-- Beginner (Bad Practice):
if player then
    if player.Team == "Red" then
        -- Do stuff
    end
end

-- Professional (Guard Clause):
if not player then return end
if player.Team ~= "Red" then return end

-- Do stuff cleanly!