Back to Course HomeLesson 6 of 19
Beginner to Intermediate • Part 1 & 2

Loops and Iteration in Lua

Lesson Overview

Automation is one of the primary goals of programming. To perform a task multiple times—whether processing thousands of data rows, updating game world entities, or waiting for user input—we use Loops.

This lesson is designed as a very long, multi-part deep dive into loops and iteration in Lua. It starts from absolute fundamentals and gradually builds toward advanced, real-world usage.

Lesson Objectives

By the end of this complete lesson series, you will be able to:

  • Understand iteration and repetition
  • Use all Lua loop types correctly
  • Control loop flow safely and efficiently
  • Avoid infinite loops
  • Write readable, optimized looping logic

What Is a Loop?

A loop is a programming structure that repeats a block of code while a condition remains true or for a specific number of times.

In human terms:

  • • Do something again
  • • And again
  • • Until a rule says stop

Real-Life Examples

  • Counting from 1 to 10
  • Reading every line in a file
  • Checking player health every frame in a game
  • Processing each item in a list

All of these require iteration.

Why Loops Are Essential

Without loops:

  • • You would repeat code manually
  • • Programs would be longer and error-prone
  • • Automation would be nearly impossible

Example Without a Loop

LUA
print(1)
print(2)
print(3)
print(4)
print(5)

Example With a Loop

LUA
local i = 1
while i <= 5 do
    print(i)
    i = i + 1
end

Loops make programs scalable and maintainable.

Types of Loops in Lua

Lua provides four main looping constructs:

whilerepeat...untilfor (numeric)for (generic)

This part focuses on the while loop, as it teaches the core looping concept used everywhere.

Understanding Iteration

Iteration means:

  • • Start at an initial state
  • • Perform an action
  • • Move toward a stopping condition

Every loop has three critical components:

  1. Initialization
  2. Condition
  3. Update
Critical: If any of these are missing or incorrect, the loop fails.

The while Loop

The while loop repeats a block of code as long as a condition is true.

Syntax

while condition do
    -- code block
end

Basic Example

LUA
local count = 1

while count <= 5 do
    print(count)
    count = count + 1
end

This loop:

  • • Starts at 1
  • • Stops after 5
  • • Updates the counter every iteration

Infinite Loops

An infinite loop occurs when the condition never becomes false.

Example (Incorrect)

LUA - DANGER
local i = 1

while i <= 5 do
    print(i)
end

This loop never updates i.

Why Infinite Loops Are Dangerous

  • Program freezes
  • CPU usage spikes
  • Game engines lock up

Corrected Example

LUA
local i = 1

while i <= 5 do
    print(i)
    i = i + 1
end

Using break in a while Loop

The break statement exits a loop immediately.

LUA
local i = 1

while true do
    print(i)
    if i == 5 then
        break
    end
    i = i + 1
end

This creates a controlled infinite loop.

Part 2: The repeat ... until Loop

A unique loop that always runs at least once

What Is a repeat ... until Loop?

A repeat ... until loop executes its code at least once, and then checks a condition after the loop body runs.

This makes it fundamentally different from a while loop, which checks the condition before executing.

Syntax of repeat ... until

repeat
    -- code block
until condition

Important rules:

  • • The loop body always runs at least once
  • • The loop stops when the condition becomes true
  • • The condition is evaluated at the end

Basic Example

LUA
local count = 1

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

Output:

Output
1
2
3
4
5

Even if count started at 10, the loop would still run once.

The Numeric for Loop

Used when you know the exact range of values to iterate over.

Syntax:

for variable = start, stop, step do
    -- code
end

Standard Increment:

for i = 1, 10, 2 do
    print(i) -- Outputs: 1, 3, 5, 7, 9
end

Reverse Iteration:

for i = 10, 1, -1 do
    print(i) -- Counts down from 10 to 1
end
Performance: The numeric for loop is the fastest in Lua because the VM optimizes it heavily.

The Generic for Loop

Designed to traverse data structures using iterator functions.

Using ipairs (Arrays):

LUA
local fruits = {"Apple", "Banana", "Cherry"}

for index, value in ipairs(fruits) do
    print("Item " .. index .. " is " .. value)
end

Using pairs (Dictionaries):

LUA
local player = {name = "Hero", level = 50, class = "Warrior"}

for key, val in pairs(player) do
    print(key .. ": " .. val)
end
Important: The order of elements in a pairs loop is not guaranteed. Lua stores keys in a hash table.

Loop Control: break and the continue Problem

The break Statement

Immediately terminates the innermost loop.

for i = 1, 100 do
    if i == 5 then break end
    print(i)
end
-- Output stops at 4

The Missing continue

Lua doesn't have continue. Use these patterns instead:

Method A: Using if (Recommended)

for i = 1, 10 do
    if i % 2 == 0 then
        print("Even number: " .. i)
    end
end

Method B: Using goto (Lua 5.2+)

for i = 1, 10 do
    if i % 2 == 0 then goto continue end
    print(i)
    ::continue::
end

Common Beginner Mistakes

  • Forgetting to update the loop variable
  • Using the wrong condition
  • Overusing nested loops
  • Not understanding loop exit flow

Ready to test your knowledge?

Take the quiz to verify your understanding of loops and iteration.