I'm making scripts that are testing around with arrays and reading a bit of the wiki said that you should use ipairs instead of pairs. Unfortunately, the articles for ipair and pair aren't very detailed and don't really help me understand what they are actually used for/ what is the difference between the two? Anyone care to explain when to use which and what the difference is?
What is the difference between pairs and ipairs?
1 answer
ipairs (a.k.a index-value-pair, or index - pair) has some distinct similarities between pairs.
ipairs and pairs are very alike, both of them are used to get pairs of values/elements in a table.
The only difference between the two, is that ipairs and pairs both have different iterators!
##How does Ipairs work?
Ipairs
Ipairs only retrieves numerical keys, meaning ipairs can only return values specified in a format.
In addition, if Ipairs retrieves any value which is non-existent/nil. It will simply stop/break the current loop and finish!
Example:
ListTable = {8, 5, nil, 9}
for i,v in ipairs(ListTable) do
print(v)
end
--[[
OUTPUT:
8
5
Notice how 9 isn't printed, because ipairs encountered a nil value.
]]
Pairs
Pairs, on the other hand, will run a statement regardless of non-numerical keys (e.g. strings).
This makes this function useful in dictionary or tables with values that contain strings or numbers.
##Here's an example of pairs:
local ListDefined = {2,4,6, "hello",nil}
for i,v in pairs(ListDefined) do
print(v)
end
--[[
OUTPUT:
2
4
6
hello
]]
References:
Scripting Helpers - What is the difference between pairs and ipairs
(The source I used for this example)
pairs v ipairs - lua users wiki
Thanks, JesseSong!
Note: This example very simple for beginners to comprehend, any enquires/inquires should be commented below!
2 comments
Edited. Fixed grammatical errors! - January 30, 2021
Refined a minor grammatical error. Date: February 19, 2021
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
This question was asked a bunch, use the search feature for very in-depth answers
Alright, sorry about that.