Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

What is the difference between pairs and ipairs?

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?

2 comments

0

This question was asked a bunch, use the search feature for very in-depth answers

0

Alright, sorry about that.

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:

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!

2 comments

0

Edited.  Fixed grammatical errors! - January 30, 2021

0

Refined a minor grammatical error. Date: February 19, 2021

This discussion is preserved as it was. New answers, comments, and votes are closed.