Lua Loops Guide — while, for, and repeat-until Control Structures
In this tutorial, you will learn about Lua Loops Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Lua loops let you repeat code execution using while (condition before body), for (numeric and generic), and repeat-until (condition after body) -- with break to exit early and goto for arbitrary jumps.
while Loop
local i = 1
while i <= 5 do
print("Count:", i)
i = i + 1
end
Numeric for Loop
-- for start, stop, step do
for i = 1, 5 do
print(i) --> 1 2 3 4 5
end
-- With step
for i = 10, 1, -2 do
print(i) --> 10 8 6 4 2
end
Generic for Loop
local fruits = {"apple", "banana", "cherry"}
-- ipairs: index-value pairs (sequential)
for i, fruit in ipairs(fruits) do
print(i, fruit)
end
-- pairs: key-value pairs (unordered)
local config = {host="localhost", port=8080}
for key, value in pairs(config) do
print(key, value)
end
repeat-until Loop
local x = 1
repeat
print(x)
x = x + 1
until x > 5
-- Body always executes at least once
break and goto
-- break exits the current loop
for i = 1, 10 do
if i > 5 then break end
print(i)
end
-- goto jumps to a label
for i = 1, 10 do
if i == 3 then goto skip end
print(i)
::skip::
end
Common Mistakes
1. Infinite loops
Forgetting to update the loop variable in a while loop: while i <= 5 do print(i) end without incrementing i.
2. Using pairs instead of ipairs
pairs on an array returns keys in arbitrary order. Use ipairs for sequential numeric indices.
3. Modifying table during iteration
Adding or removing elements while iterating with pairs or ipairs causes undefined behavior.
Practice Questions
1. What is the difference between pairs and ipairs? ipairs iterates over sequential integer keys (1..n). pairs iterates over all keys in arbitrary order.
2. When does a repeat-until loop execute? The body executes first, then the condition is checked. The body always runs at least once.
3. How do you exit a loop early?
Use break to exit the innermost loop immediately.
FAQ
{{< faq question="Can I break out of nested loops?" >}} break exits only the innermost loop. Use a flag variable or goto to break out of nested loops. {{< /faq >}}
{{< faq question="Is the numeric for loop inclusive?" >}}
Yes. for i = 1, 5 do includes both 1 and 5. The loop variable is local to the loop body.
{{< /faq >}}
{{< faq question="What happens if step is 0?" >}} An infinite loop. Lua does not check for zero step. Always use non-zero step values. {{< /faq >}}
What's Next
Now learn about advanced table operations.
| Topic | Description | Link |
|---|---|---|
| Tables Advanced | Table functions and operations | {{< ref "19-tables-advanced" >}} |
| File I/O | Reading and writing files | {{< ref "09-file-io" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro