Should I use ipairs for iterating through objects/models and pairs for iterating through a dictionary?

Hi!
Someone told me that I should use ipairs for iterating through objects/models and arrays and pairs for iterating through a dictionary but most of the people just use pairs for pretty much everything. So does it even make sense using ipairs or not? Thanks.

ipairs is for iterating over arrays with numerical indices starting at 1, so yes.

GetChildren() and GetDescendants() both return arrays, so when you are iterating through children or descendants of a model it is safe to use ipairs.

1 Like

The difference is that ipairs loop can’t detect key-value pairs in a table, unlike pairs loop, which is why pairs loop is preferred in dictionaries.

ipairs is still useful if you want only index-value pairs.

1 Like

So if I’m iterating through a table that goes like this

local t = {
"Bruh";
"Hi";
"Lol";
"Idk";
}

It might be that Idk is first and Lol is second if I’m using pairs instead of ipairs?

What do you mean with key-value pairs?

That is an array, since the keys are implicitly numbers. In this example regardless of whether you use pairs or ipairs the key-value pairs will be:

1    "Bruh"
2    "Hi"
3    "Lol"
4    "Idk"

In a table such as this:

local x = {
["hello"] = 3,
[0] = 5,
[game.Workspace] = Vector3.new(0, 0, 0)
}

The keys are mixed. ipairs won’t work on this one. The table can still be iterated over with pairs, but the order may not be guaranteed to be the same as how it is hard-coded.

1 Like

Basically like this:

local Dictionary = {
    Key = "Blah Blah Blah",
    Value = "Blah"
}

You assign a non numerical index to the value.

1 Like

Edit: oh nevermind, it’s the first one. Index

There is also one more thing that’s important to mention and it’s that ipairs loop stops when it encounters a nil value, unlike pairs loop.

3 Likes