You shouldn’t use them interchangeably, as they have different behaviour when you really try them.
The difference is, with ipairs, you only traverse the array part of a table, and if nil is encountered, ipairs, or I should say the function it returns, stops in its tracks.
Here is an example:
t = {9.734, 8, nil, "nice"}
for _, v in ipairs(t) do
print(v)
end
Output
9.734
8
If you want to guarantee order, use ipairs/numeric for loop.
Apologies for the bump - just have a follow-up question.
I’ve seen countless explanations of the differences between pairs and ipairs, but no explanation as to when we would actually want to rather use ipairs over pairs.
Isn’t the guaranteed “safety” of the pairs loop, as well as its ability to pinpoint multiple nil values after the first nil has been found, much better than that of ipairs, which just ends as soon as it sees a nil in the array?
Personally, I would just perform a pairs loop and check for nil if I ever had an array that had the possibility of having nil values. So perhaps there is no big difference, and it just depends on your preferred coding style?
Oh trust me, I tried doing the research before necrobumping - one thing I did find on a devforum post was that using ipairs is recommended for finding the indices of a table… but again I feel that it’s easier to just use pairs, or honestly probably just a regular for loop for that. I don’t see the situations where using ipairs is more beneficial.
I guess I just want to know some applications / real-world examples of using ipairs, because it seems somewhat irrelevant for most cases - unless, as I said, it’s just a preference thing! Or maybe, I’m completely missing a key aspect of ipairs that makes it better in certain cases…
Using ipairs just shows you’re working with arrays, it’s even designed just for that (doesn’t work with non-numeric indices since in the iterator function ipairs returns, a number is incremented until #t and the index and value is returned as i, t[i] - and non-numeric indices are not the same as numeric ones ).
There’s only negligible difference in the amount of time it takes iterating in ipairs than pairs (former is faster (and faster in Luau as well in general), recommended to be used with arrays) .
pairs I noticed does guarantee order even when iterating through arrays, this is probably something relatively new with Luau.
Sorry for the bump, but I think here is what ipairs() function means
Lets say you have a table, and you want to order it by its index
You can use ipairs() to iterate through it by the index
local dict = {
["A"] = 10,
[5] = "Order",
["XYZ"] = 30,
[4] = "Correct",
["ABC"] = 100,
[2] = "Is",
[3] = "The",
[1] = "This",
}
for key, value in ipairs(dict) do
print(key, value)
end
OUTPUT:
1 This
2 Is
3 The
4 Correct
5 Order
Thats why it always works on “arrays”, since arrays are basically like dictionaries except their keys starts from Index 1
Hopefully this could help