Difference between pairs() and ipairs()

What’s the difference from pairs() and ipairs()? I typically only use pairs(), but could ipairs be more useful in different situations?

1 Like

Actually I have also thought about that but here is a dev hub post of pairs and ipairs.

pairs and iPairs

ipairs expects the indices to be sequential. It will stop when there is a gap.

Pairs can go over an array too though, can’t it?

yes, but ipairs goes in order.

1 Like

Could I have an example situation of when this would be useful?

You would use ipairs on arrays when you need the results in a particular/linear order, say for example your creating a shop gui and want the elements to be created and shown in a particular order you could store the data in a array in the desired order, and iterate over it in the correct order using ipairs, the pairs iterator returns the items in any order, and should really be used for dictionaries.

1 Like

If you want to check if something’s correctly ordered, you’d want to loop through it in the order the list is in. You might also have a mixed table and just want to loop through the numeric part for some reason.

5 Likes

I heard that ipairs is faster than pairs is that true?

1 Like

Dictionaries can use integer keys, but ipairs will stop once there is a gap.

local dict = {
    [1] = "Lemon",
    [2] = "Yellow",
    [3] = true,
    [5] = "ipairs won't see this one or any after it"
}

Using pairs on an array should still iterate over all the items (although potentially not in the order you expect). Using ipairs on a dict should probably be avoided. Arrays can be stored more efficiently than dictionaries and can be faster in some languages (depending on implementation). I don’t know how Lua implements tables or how it handles arrays vs dicts under the hood. There may or may not be a performance advantage to using ipairs with arrays, but to avoid running into any unexpected behavior, use ipairs with arrays and pairs with dictionaries.

9 Likes