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

What are the Differences between "Pairs", "Next" and "IPairs"?

Asked by
woodengop 1134 Moderation Voter
9 years ago

I Apologize if this Question has been already asked, But This would DEEPLY Help me in my Study. What are the Differences Between Pairs,iPairs, and Next? I've seen these three written with a in as the Beginning. like:

- in pairs

- in ipairs

- in next

1 answer

Log in to vote
4
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

They are all iterator functions, used in generic for loops.

ipairs iterates through the integer keys of a Table, starting at 1 and stopping when the next consecutive integer key has a value of nil:

local t = {"gradea", 245, false}
t[6] = "This string won't be reached"

for key, value in ipairs(t) do
    print(key)
    print(value)
end

pairs and next are, effectively, the exact same thing. next is faster, slightly, since pairs uses next internally. They iterate through all members of a Table, but in an undetermined order (between server instances, that is):

local privateKey = {}
local t = {someStringKey = false, [24] = 16, [privateKey] = "swaggy", 1325, false, "anchored"}

for key, value in pairs(t) do
    print(key)
    print(value)
end
--This is, basically, the same as:
for key, value in next, t do
    print(key)
    print(value)
end

These iterators work with Tables. I used 'random' data in my Tables, so sorry if that confused you.

ipairs works, effectively, like this:

local index = 1 --index is another word for 'key'.
local t = {"gradea", 245, false}
t[6] = "This string won't be reached"

while t[index] ~= nil do --~= nil is necessary here because values of `false` are important. `(false ~= nil) == true` Only `nil` Values stop the loop.
    print(t[index])
    index = index + 1
end

That while loop will print the values of t using only consecutive integer keys, starting at 1.

In my Table t, keys 1, 2, 3, and 6 have defined values, so the while loop (and thus, ipairs), will print the values at t[1], t[2], and t[3] and then stop because t[4] == nil.

0
so ipairs works more with the Strings? woodengop 1134 — 9y
0
I think he means that ipairs goes through the loop until there is a predefined variable that takes place of the key that is not a integer/number. Though I could be wrong. M39a9am3R 3210 — 9y
0
Sorta. I'll add some pseudocode for ipairs for further explanation. adark 5487 — 9y
Ad

Answer this question