4.3 The for Loop: Numeric

The while loop is useful when we need a loop that runs for an indeterminate number of times. But what if we already know how many times we want to run a loop for?

Yes, sure, we can create some counter variable and track the number of times a loop has gone around.

But it’s rather clunky given that the counter is declared at one place, checked against the condition somewhere else, and modified at a third location. Plus we still have that counter variable that hangs around after the loop has completed.

We need a loop that does something for a specified number of times.

This determinate type of loop is used often enough that it merits its own implementation. We call it the ‘for‘ loop.

Lua
for counter = 1, 10 do
	print(counter)
end
--[[ Output:
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
]]

counter,‘ as we did before, is the iterator name and is initialized to 1. 10 is the iterator max.

However, you won’t often see this variable named as ‘counter.’ Out of convention (and from mathematics), ‘i‘ is the iterator name you’ll see most often, followed by ‘j.’

The iterator can be initialized to any integer value and because this is a local variable, it’s visible anywhere inside the loop, including nested loops.

Here is an example of a for loop nested inside another—both beginning and ending at different values.

Lua
for i = 10, 15 do
	for j = 13, 16 do
		print(i, j)
	end
end
--[[ Output:
  10 13
  10 14
  10 15
  10 16
  11 13
  ...
  ...
  ...
  14 16
  15 13
  15 14
  15 15
  15 16
]]

By default the iterator increments by one. You can change the increment/decrement amount by adding a third argument.

Lua
for i = 20, 1, -3 do
	print(i)
end
--[[ Output:
  20
  17
  14
  11
  8
  5
  2
]]

Arrays are powerful but only if we have a way to access its individual elements. Keys and indices are not something we usually keep track of.

With an indexed array, you can use the numeric for loop to iterate though each of the elements.

Like with the while loop, the break statement can be used to exit a loop.

Lua
local someList = {math.random(), math.random(), math.random(), math.random()}

for i = 1, #someList do
	print(someList[i])
	
	if i >= 3 then
		break
	end
end

When you need to perform a large number of similar operations, such as creating a large number of parts, this is your go-to loop.

Lua
game:GetService("Lighting").ClockTime = 0

local partsList = {}
local folder = Instance.new("Folder")
folder.Parent = game.Workspace

for i = 1, 100 do
	local part = Instance.new("Part")
	part.Shape = Enum.PartType.Ball
	part.Material = Enum.Material.Neon
	part.BrickColor = BrickColor.random()
	part.Position = Vector3.new(math.random(-100, 100), math.random(50), math.random(-100, 100))
	part.Anchored = true
	part.Parent = folder
	
	local light = Instance.new("PointLight")
	light.Color = part.BrickColor.Color
	light.Brightness = 5
	light.Range = 16
	light.Parent = part

	partsList[i] = part
end