beginner
20 min

Control Flow: If Statements & Loops

Master conditional statements and loops to control the flow of your scripts.

If/ElseFor LoopsWhile Loops

1
If Statements

If statements allow you to execute code only when certain conditions are met.

Basic If Statement

local health = 50

if health < 100 then
  print("Health is low!")
end

The code inside the if block only runs when the condition is true.

If-Else Statement

local score = 85

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

Use elseif for multiple conditions and else for a default case.

💡 Tips:

  • • Comparison operators: == (equal), ~= (not equal), <, >, <=, >=
  • • Logical operators: and, or, not

2
For Loops

For loops repeat code a specific number of times.

Numeric For Loop

-- Count from 1 to 10
for i = 1, 10 do
  print("Number: " .. i)
end

-- Count with step
for i = 0, 100, 10 do
  print(i)  -- 0, 10, 20, 30...
end

Format: for variable = start, end, step. Step is optional (default is 1).

Generic For Loop (Tables)

local players = {"Alice", "Bob", "Charlie"}

for index, name in ipairs(players) do
  print(index .. ": " .. name)
end

Use ipairs() to iterate through array-like tables with indices.

3
While Loops

While loops repeat code as long as a condition is true.

While Loop

local count = 1

while count <= 5 do
  print("Count: " .. count)
  count = count + 1
end

Be careful to update the condition variable, or you'll create an infinite loop!

Repeat-Until Loop

local num = 1

repeat
  print(num)
  num = num + 1
until num > 5

Similar to while, but checks condition AFTER each iteration (runs at least once).

💡 Tips:

  • • Use for loops when you know how many iterations
  • • Use while loops when the condition determines the end
  • • Be careful with infinite loops - they can crash your game!

Practice Exercises

Exercise 1: Health Check System

Create an if statement that checks health and prints different messages.

Starter Code:

local health = 45

-- Write your if statement here
Show Solution
local health = 45

if health > 75 then
  print("Health is good!")
elseif health > 25 then
  print("Health is okay")
else
  print("Critical health!")
end

Exercise 2: Countdown Timer

Use a for loop to create a countdown from 10 to 1.

Starter Code:

-- Create a countdown loop

print("Liftoff!")
Show Solution
for i = 10, 1, -1 do
  print(i)
  wait(1)  -- Wait 1 second between counts
end

print("Liftoff!")

Ready for more?

Continue your learning journey

Executors.Online - Your Roblox Developer Hub