Loops in Lua

Loops allow you to repeat code execution multiple times. Lua provides three main loop types: while, for, and repeat-until. Each serves different purposes for iteration.

While Loop

The while loop repeats as long as a condition is true:

local count = 1

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

-- Output:
-- Count: 1
-- Count: 2
-- Count: 3
-- Count: 4
-- Count: 5

Use when: You don’t know how many iterations you’ll need in advance.

-- Reading until valid input
local input
while input ~= "quit" do
    input = io.read()
    if input ~= "quit" then
        print("You typed:", input)
    end
end

Numeric For Loop

The numeric for loop iterates over a range of numbers:

for i = 1, 5 do
    print("Iteration:", i)
end

-- Output:
-- Iteration: 1
-- Iteration: 2
-- Iteration: 3
-- Iteration: 4
-- Iteration: 5

For Loop with Step

Control the increment/decrement with a step value:

-- Counting by 2s
for i = 2, 10, 2 do
    print(i)
end
-- Output: 2, 4, 6, 8, 10

-- Counting backwards
for i = 5, 1, -1 do
    print("Countdown:", i)
end
-- Output: 5, 4, 3, 2, 1

Use when: You need to iterate a known number of times.

Generic For Loop (Pairs and Ipairs)

Iterate over tables using generic for loops:

Ipairs (for arrays)

local fruits = {"apple", "banana", "orange", "grape"}

for index, value in ipairs(fruits) do
    print(index, value)
end
-- Output:
-- 1  apple
-- 2  banana
-- 3  orange
-- 4  grape

Pairs (for dictionaries)

local person = {
    name = "Alice",
    age = 30,
    city = "New York"
}

for key, value in pairs(person) do
    print(key, value)
end
-- Output (order may vary):
-- name    Alice
-- age     30
-- city    New York

Repeat-Until Loop

The repeat-until loop executes code until a condition becomes true:

local number
repeat
    print("Enter a positive number:")
    number = tonumber(io.read())
until number and number > 0

print("You entered:", number)

Key difference: The condition is checked after the loop body, so it always executes at least once.

Loop Control

Break Statement

Exit a loop early using break:

for i = 1, 100 do
    if i > 5 then
        break
    end
    print(i)
end
-- Output: 1, 2, 3, 4, 5

Finding Items

local fruits = {"apple", "banana", "orange", "grape"}
local target = "orange"
local found = false

for i, fruit in ipairs(fruits) do
    if fruit == target then
        found = true
        print("Found", target, "at position", i)
        break
    end
end

if not found then
    print(target, "not found")
end

Nested Loops

Loops can be nested inside other loops:

for i = 1, 3 do
    for j = 1, 3 do
        print(i, "x", j, "=", i * j)
    end
end

-- Output:
-- 1 x 1 = 1
-- 1 x 2 = 2
-- 1 x 3 = 3
-- 2 x 1 = 2
-- 2 x 2 = 4
-- 2 x 3 = 6
-- 3 x 1 = 3
-- 3 x 2 = 6
-- 3 x 3 = 9

Practical Examples

Summing Numbers

-- Sum numbers from 1 to 100
local sum = 0
for i = 1, 100 do
    sum = sum + i
end
print("Sum:", sum)  -- 5050

Finding Maximum Value

local numbers = {45, 23, 78, 12, 89, 34}
local max_value = numbers[1]

for i = 2, #numbers do
    if numbers[i] > max_value then
        max_value = numbers[i]
    end
end

print("Maximum value:", max_value)  -- 89

Table Processing

local users = {
    {name = "Alice", age = 30},
    {name = "Bob", age = 25},
    {name = "Charlie", age = 35}
}

for i, user in ipairs(users) do
    if user.age >= 30 then
        print(user.name, "is", user.age, "years old")
    end
end

Input Validation Loop

local password
local attempts = 0
local max_attempts = 3

repeat
    print("Enter password:")
    password = io.read()
    attempts = attempts + 1
    
    if password ~= "secret" and attempts < max_attempts then
        print("Wrong password. Try again.")
    end
until password == "secret" or attempts >= max_attempts

if password == "secret" then
    print("Access granted!")
else
    print("Too many attempts. Access denied.")
end

Loop Patterns

Infinite Loop (with break)

while true do
    print("Processing...")
    -- Some condition to break
    if some_condition then
        break
    end
end

Iterating with Index and Value

local items = {"a", "b", "c"}

for i, v in ipairs(items) do
    print("Item", i, "is", v)
end

Processing Until Condition

local data = {10, 20, 30, 40, 5}
local i = 1

while i <= #data do
    if data[i] < 10 then
        print("Found small number:", data[i])
        break
    end
    i = i + 1
end

Best Practices

  1. Choose the right loop type for your use case
  2. Use meaningful variable names in loops (i, j, k are fine for simple counters)
  3. Avoid infinite loops unless you have a clear break condition
  4. Prefer for loops when you know the iteration count
  5. Use break sparingly - consider restructuring your logic instead

Next Steps

Now that you understand loops, learn about functions to organize your code into reusable blocks.

For more loop details, see the Lua manual.

Last updated on