Lua Goto and Labels Guide — Advanced Flow Control and Jump Statements
In this tutorial, you will learn about Lua Goto and Labels Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Lua goto statement (Lua 5.2+) uses ::label:: syntax for unconditional jumps within the same function -- enabling early exit from nested loops, state machine patterns, and cleanup code that runs before function return.
Basic Goto Syntax
-- Label is defined with ::
::restart::
local input = io.read()
if input == "" then
goto restart -- jump back
end
Breaking from Nested Loops
-- break only exits the innermost loop
-- goto can exit multiple levels
for i = 1, 10 do
for j = 1, 10 do
if i * j > 50 then
goto found
end
end
end
::found::
print("Found pair with product > 50")
State Machine Pattern
local state = "init"
::init::
print("Initializing...")
state = "process"
goto process
::process::
print("Processing...")
state = "cleanup"
goto cleanup
::cleanup::
print("Cleaning up...")
-- end of state machine
Error Recovery
local ok, result = pcall(function()
error("temporary failure")
end)
if not ok then
goto retry
end
::retry::
print("Attempting operation...")
Common Mistakes
1. Jumping into a block scope
Cannot goto into a scope that skips variable initialization: goto into a loop body or past a local declaration.
2. Using goto where structured flow works
Prefer if/else, break, and loops. goto is for cases where those are insufficient.
3. Labels with same name in same function
Labels must be unique within a function scope. Duplicate labels cause a compile error.
Practice Questions
1. What limitation does goto have regarding scope? goto cannot jump into the scope of a local variable (past a local declaration) or into a loop/block body.
2. When should you use goto instead of break? When you need to break out of nested loops (break only exits the innermost loop).
3. Can you goto outside the current function? No, goto is limited to jumps within the same function. Cross-function jumps are not allowed.
FAQ
{{< faq question="Is goto considered harmful in Lua?" >}} goto is rarely needed. Use it only for escaping nested loops or implementing state machines. Overuse makes code hard to follow. {{< /faq >}}
{{< faq question="Can I use goto with coroutines?" >}} goto cannot yield or jump across Coroutine boundaries. Each coroutine has its own goto scope. {{< /faq >}}
{{< faq question="How is ::label:: different from C's goto?" >}}
Lua labels use ::name:: syntax. The restriction against jumping over local declarations is similar to C's restriction with VLAs.
{{< /faq >}}
What's Next
Now that you've completed the Lua tutorial series, explore other languages.
| Topic | Description | Link |
|---|---|---|
| Perl | Start learning Perl | Perl |
| Python | Compare with Python | Python |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro