4.4 The for Loop: Generic

The numeric for loop works as a general iterative loop and when you want to iterate through an array of continuous sequential elements. But elements of something like a sparse array or key-value pair will be omitted because of their non-sequential nature.

A different type of for loop is required for this.

Lua
local list = {
	["apple"] = math.random(),
	["orange"] = math.random(),
	["lemon"] = math.random(),
	[1] = 3.14, 
	[2] = "Hello world!",
	[4] = 42
}

for k, v in pairs(list) do
	print(k, v)
end

The generic “pairs” loop iterates through every element of a table.

With this loop, you will often see ‘k‘ and ‘v‘ representing the key-value variables. ‘pairs‘ is called the iterator function and takes a table/array argument then returns the table’s keys and values.


A variation to the ‘pairs‘ function is the ‘ipairs‘ function. This iterates through just the indexed array, beginning at index 1 until the end of the array or it encounters a hole.

Lua
local list = {
	["apple"] = math.random(),
	["orange"] = math.random(),
	["lemon"] = math.random(),
	[1] = 3.14, 
	[2] = "Hello world!",
	[4] = 42,
}

for k, v in ipairs(list) do
	print(k, v)
end

Because the ‘GetChildren‘ method returns an array, for loops are often used to iterate through the list.

Lua
local children = game.Workspace:GetChildren()

for __, v in ipairs(children) do
	print(v)
end

You might encounter a single or double underscore character used in place of an expected variable. This is a legal variable name but more importantly, it is meant to indicate a “throwaway” variable because the value will not be used.