For clearer explanation:
Roblox uses a modification of Lua
and is called Luau
.
In older versions, Luau
didn’t have generalised for
loops.
Before the update, you’d have to use pairs()
and other iterator functions, i.e ipairs()
, next()
.
You’ll notice that if you attempt to write a generalised for
loop in Lua
and not Luau
, you’ll get an error. Generalised for
loops are exclusive to Luau
.
What pairs()
does is return a tuple (a, b)
in the form key/index, value
.
A key
is essentially the name given to a value
in a dictionary
, i.e the hello
in {hello = 1}
An index
is a number-type key
assigned to a value in an array
. You can either specify it explicitly (directly setting the indexes) or implicitly (leaving it blank).
local explicitIndexes = {
[1] = "nice",
[2] = "wow",
[3] = "fantastique"
}
--explicitIndexes[1] = "nice"
--explicitIndexes[2] = "wow"
--explicitIndexes[3] = "fantastique"
local implicitIndexes = {"value", "hello", 9}
--implicitIndexes[1] = "value"
--implicitIndexes[2] = "hello"
--implicitIndexes[3] = 9
The value
is what is given as an equals
operation, i.e the 1
in {hello = 1}
In short, pairs()
returns a key/index-value pair
.
ipairs()
(short for indexpairs) on the other hand returns an index-value pair
. If you give a table with a string key to ipairs()
, it will error.
This is also why it says in
.
in pairs()
→ in pairs
in ipairs()
→ in index pairs
If you decide to use generalised for
loops, it will default to using `pairs()’.
Hope this helps!