Lua in Neovim: Break and Nested Loops — Star Patterns & Finding Divisible Numbers | Episode 11
Video: Lua in Neovim: Break and Nested Loops — Star Patterns & Finding Divisible Numbers | Episode 11 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lua in Neovim: Break and Nested Loops — Star Patterns & Finding Divisible Numbers
Master loop control in Lua by using break to exit loops early and nested for loops to create star patterns. This example demonstrates building a star rectangle and triangle, plus finding the first number divisible by both 7 and 13, illustrating how break affects only the innermost loop.
Code
-- Star Rectangle: 5 rows, 10 columns
for row = 1, 5 do
local line = ""
for col = 1, 10 do
line = line .. "*"
end
print(line)
end
print() -- blank line
-- Star Triangle: rows with increasing stars
for row = 1, 5 do
local line = ""
for col = 1, row do
line = line .. "*"
end
print(line)
end
print() -- blank line
-- Find first number divisible by both 7 and 13 between 1 and 200
for num = 1, 200 do
if num % 7 == 0 and num % 13 == 0 then
print("First number divisible by 7 and 13 is:", num)
break -- exits this loop immediately
end
end
Key Points
breakimmediately exits the current (innermost) loop when executed.- Nested loops run one loop inside another, with each loop having its own independent counter.
- Star patterns can be created by controlling the number of iterations in nested loops.
- Using
breakinside nested loops only stops the innermost loop, not outer loops. - Nested loops are useful for building grids, tables, and searching through combinations efficiently.