Loops & Control Flow in Lua
Learn about loops, conditionals, and program flow control in Lua
For Loops
For loops are used to iterate through a sequence of values. In Lua, there are two types of for loops: numeric for and generic for.
numeric_for.lua
-- Numeric for loop
for i = 1, 5 do
print(i)
end
-- With step value
for i = 10, 1, -2 do -- Count down by 2
print(i) -- Prints: 10, 8, 6, 4, 2
end
generic_for.lua
-- Generic for loop with ipairs (array-like iteration)
local fruits = {"apple", "banana", "orange", "grape"}
for index, value in ipairs(fruits) do
print(index .. ": " .. value)
end
-- Generic for with pairs (table iteration)
local person = {
name = "Aidan",
age = 25,
job = "Developer"
}
for key, value in pairs(person) do
print(key .. ": " .. value)
end
While Loops
A while loop repeats a block of code as long as a specified condition is true.
while_loop.lua
-- Basic while loop
local count = 1
while count <= 5 do
print(count)
count = count + 1
end
-- Using while for input validation (pseudo-code)
--[[
local input
while not isValid(input) do
input = getInput()
if not isValid(input) then
print("Invalid input, try again")
end
end
--]]
Repeat-Until Loops
Repeat-until loops are similar to while loops, but they execute the block at least once and continue until the condition is true.
repeat_until.lua
-- Basic repeat-until loop
local count = 1
repeat
print(count)
count = count + 1
until count > 5
-- Good for input validation
--[[
local input
repeat
input = getInput()
if not isValid(input) then
print("Invalid input, try again")
end
until isValid(input)
--]]
Conditional Statements
Conditional statements allow your program to make decisions based on conditions.
if_statements.lua
-- Basic if statement
local playerHealth = 75
if playerHealth >= 75 then
print("Player health is good!")
elseif playerHealth >= 25 then
print("Player health is low!")
else
print("Player is in danger!")
end
-- One-liner for simple conditions
if playerHealth <= 0 then return end -- Exit early if player is defeated
-- Complex conditions with logical operators
local hasShield = true
local hasPotion = false
if playerHealth < 50 and hasPotion then
print("Use your potion!")
elseif playerHealth < 30 and not hasShield then
print("You are vulnerable, take cover!")
end
Breaking and Continuing Loops
Lua provides ways to control the flow of loops with break
and goto
statements.
loop_control.lua
-- Breaking out of a loop
for i = 1, 10 do
if i > 5 then
break -- Exit the loop early
end
print(i)
end
-- Using goto for more complex flow control (Lua 5.2+)
for i = 1, 10 do
if i % 2 == 0 then
goto continue -- Skip even numbers
end
print(i) -- Only prints odd numbers
::continue::
end
Practical Example: Game Looping
Here's a practical example of using loops and control flow in a game context:
game_loop.lua
-- Simple game loop
local isGameRunning = true
local playerHealth = 100
local enemyCount = 5
local score = 0
-- Main game loop
while isGameRunning do
-- Process player input (pseudo-code)
local action = getPlayerAction()
-- Update game state
if action == "attack" then
enemyCount = enemyCount - 1
score = score + 100
if enemyCount <= 0 then
print("Level complete! Final score: " .. score)
isGameRunning = false
end
elseif action == "hit" then
playerHealth = playerHealth - 10
if playerHealth <= 0 then
print("Game over! Final score: " .. score)
isGameRunning = false
end
elseif action == "quit" then
print("Game exited. Score: " .. score)
isGameRunning = false
end
-- Render game (pseudo-code)
render()
-- Wait for next frame (pseudo-code)
wait(1/60) -- 60 FPS
end
Break and Continue
Lua provides keywords to control loop execution flow.
break_continue.lua
-- Break statement exits the loop
for i = 1, 10 do
if i > 5 then
break -- Exit the loop when i > 5
end
print(i)
end
-- Simulating continue with goto (Lua doesn't have "continue")
for i = 1, 10 do
if i % 2 == 0 then
goto continue -- Skip even numbers
end
print(i) -- This only prints odd numbers
::continue::
end