Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What is the difference between pairs and ipairs?

Asked by 9 years ago

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?

0
This question was asked a bunch, use the search feature for very in-depth answers Perci1 4988 — 9y
0
Alright, sorry about that. ghostblocks 74 — 9y

1 answer

Log in to vote
0
Answered by
JesseSong 3916 Moderation Voter Community Moderator
4 years ago
Edited 3 years ago

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:

pairs v ipairs

Scripting Helpers - What is the difference between pairs and ipairs

(The source I used for this example)

pairs v ipairs - lua users wiki

lua pil

Thanks, JesseSong!

Note: This example very simple for beginners to comprehend, any enquires/inquires should be commented below!

0
Edited.  Fixed grammatical errors! - January 30, 2021 JesseSong 3916 — 3y
0
Refined a minor grammatical error. Date: February 19, 2021 JesseSong 3916 — 3y
Ad

Answer this question