Back to Blog

Learn Lua in Neovim: Numeric For Loops — Count, Step & Countdown | Episode 9

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Numeric For Loops — Count, Step & Countdown | Episode 9 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Numeric For Loops — Count, Step & Countdown

Lua's numeric for loops let you repeat code with a controlled counter, making tasks like counting, stepping, and countdowns straightforward. This guide demonstrates basic counting, stepping by twos, counting down with a negative step, building a multiplication table, and summing numbers from 1 to 100.

Code

-- Basic counting loop from 1 to 5
for i = 1, 5 do
  print(i)  -- prints: 1 2 3 4 5
end

-- Counting by twos from 2 to 10 using a step value
for i = 2, 10, 2 do
  print(i)  -- prints: 2 4 6 8 10
end

-- Countdown from 5 to 1 using a negative step
for i = 5, 1, -1 do
  print(i)  -- prints: 5 4 3 2 1
end
print("Go!")

-- Multiplication table for 7 from 1 to 10
for i = 1, 10 do
  print("7 x " .. i .. " = " .. (7 * i))
end

-- Sum numbers from 1 to 100 using an accumulator
local sum = 0
for i = 1, 100 do
  sum = sum + i
end
print("Sum = " .. sum)  -- prints: Sum = 5050

Key Points

  • The syntax for i = start, stop do repeats code with a loop variable from start to stop.
  • Adding a third argument sets the step size, allowing you to skip numbers or count backwards.
  • Negative step values let you count down from a higher number to a lower one.
  • The loop variable i is local to the loop and changes each iteration.
  • Numeric for loops are useful for building tables, performing repeated calculations, and accumulating sums.