Syntax
for index = 1, 3 do
print(index)
endExamples
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) -- 11Remove 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, 3Best 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.
Runtime & versions
Luau host; Roblox engine examples require Roblox Studio. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Luau documentation