Codectionary / Developer documentation / Luau

Loops and iteration

Choose a numeric for loop for a known range, a table iterator for a collection, or a while loop for a condition. break leaves the loop and continue skips the rest of one iteration. Repeated engine work needs a schedule, not an unbounded busy loop.

Syntax

for index = 1, 3 do
    print(index)
end

Examples

Skip without changing the collection

Standalone Luau or a Script in ServerScriptService. Only positive values contribute to the total. The input array remains unchanged.

local values = {4, -2, 7, 0}
local total = 0
for _, value in ipairs(values) do
    if value <= 0 then
        continue
    end
    total += value
end
print(total) -- 11

Remove entries safely

Traverse backwards when removing array elements by index. Shifting a later element cannot make this loop skip an unvisited entry.

local values = {1, 2, 3, 4}
for index = #values, 1, -1 do
    if values[index] % 2 == 0 then
        table.remove(values, index)
    end
end
print(table.concat(values, ", ")) -- 1, 3

Best practices

  • Do not assume pairs produces sorted keys.
  • Use a bounded loop for a finite task, and disconnect event-driven work when its owner disappears.
  • For continuous Roblox work, choose an appropriate RunService event or task delay rather than while true without yielding.

At a glance

Purpose
Typed scripting and Roblox development
File extension
.luau
Runs in
Luau host; Roblox engine examples require Roblox Studio
Usually used with
Roblox APIs and Studio

Specifications & further reading

Related Luau documentation