Control Flow & Branching
Learn how PyLua handles conditional branches, iteration, loops, labels, and how the bytecode compiler translates control structures into high-performance VM jump opcodes.
1. Conditional Statements: `if` / `elseif` / `else`
PyLua supports both C-style curly brace syntax and traditional Lua then ... end syntax. Both compile down to identical VM bytecode instructions:
Modern C-Style Braces (Recommended)
health = 75
if (health > 80) {
print("Status: Excellent")
} elseif (health > 30) {
print("Status: Injured")
} else {
print("Status: Critical Danger!")
}
Traditional Lua Syntax (100% Backward Compatible)
if health > 80 then
print("Status: Excellent")
elseif health > 30 then
print("Status: Injured")
else
print("Status: Critical Danger!")
end
2. While Loops
Executes its block repeatedly as long as the condition evaluates to truthy (neither false nor nil):
count = 5
while (count > 0) {
print("T-Minus: " .. count)
count = count - 1
}
print("Liftoff!")
3. Repeat-Until Loops
A post-test loop that executes the body at least once. Unlike while, the loop repeats until the condition becomes true:
tries = 0
repeat
tries = tries + 1
success = attemptNetworkConnection()
until success or tries >= 5
The condition expression in an until clause has full lexical access to local variables declared inside the repeat block.
4. Numeric For Loops
Iterates an index variable from a starting value to an ending limit with an optional step (defaulting to 1):
-- Syntax: for var = start, stop [, step] { ... }
for i = 1, 10, 2 {
print("Odd number: " .. i) -- 1, 3, 5, 7, 9
}
-- Counting backwards with negative step:
for countdown = 10, 1, -1 {
print("Countdown: " .. countdown)
}
The loop variable i is strictly local to the loop body and treated as a read-only variable. Modifying it inside the loop body is not permitted and will not alter the iteration sequence.
5. Generic For Loops: Iterating Tables & Collections
Iterates over data structures using an iterator generator function:
scores = { Alice = 95, Bob = 82, Charlie = 88 }
-- Iterate all key-value pairs in a hash table:
for name, score in pairs(scores) {
print(name .. " scored " .. score)
}
inventory = { "Sword", "Shield", "Health Potion" }
-- Iterate an array part in numerical order (1..N):
for index, item in ipairs(inventory) {
print(index .. ": " .. item)
}
6. Break, Goto & Labels
Use break to immediately exit any enclosing loop. Use goto to jump directly to a label defined by double colons:
for y = 1, 10 {
for x = 1, 10 {
if (map[y][x] == "TREASURE") {
print("Found treasure at " .. x .. "," .. y)
goto found -- Multi-level loop break
}
}
}
::found::
print("Resuming execution...")
A goto jump cannot enter the scope of a local variable where that variable was not already visible before the jump point.
7. How the Backend Manages Control Flow Opcodes
In src/parser/impl/lparser_stat.c and src/runtime/lvm.c, control flow statements do not create AST branch objects at runtime. Instead, the compiler generates a linear array of instructions using jump fixup chains (luaK_patchlist):
| Statement | Primary Bytecode Opcodes | Execution Mechanics |
|---|---|---|
if (cond) |
OP_TEST / OP_TESTIFTRUE → OP_JMP |
Tests whether register R(A) is boolean true. If false, executes a relative jump skipping the then block. |
for i = s, e, step |
OP_FORPREP → [Body] → OP_FORLOOP |
Allocates 3 hidden registers: (initial, limit, step). OP_FORLOOP increments the index and branches backwards until limit is reached. |
for k, v in pairs() |
OP_TFORPREP → OP_TFORCALL → OP_TFORLOOP |
Allocates 3 registers: (generator_func, state_table, initial_key). OP_TFORCALL executes the iterator and OP_TFORLOOP checks if key is not nil. |