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

What is the difference between `ipairs` and `pairs`?

Asked by 7 years ago

The Roblox Wiki says that the way to use GetChildren() to change the properties of multiple objects at once is like this:

children = workspace:GetChildren()
for _, child in ipairs(children) do
    --code
end

This works all fine and dandy, but I've also seen it like this:

children = workspace:GetChildren()
for _, child in pairs(children) do
    --code
end

This, too, works. So what is the difference between the two? The Wiki's description is confusing and unhelpful.

2 answers

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

I've wondered this too, and what I can gather from the Lua webpage directly is that ipairs goes through an array in order from 1 to 10 and so forth while pairs will attach itself to everything in the array once but no matter numerical order. In other words, it's like saying ipairs uses #t to go through the table.

t={[1]='derp', [7]='derp', [13]='derp'}

for i=1, #t do
    print(i)
end

The output of this is 1 and only 1 because it only went through entries 1-3. ipairs does the same thing.

t={[1]='derp', [7]='derp', [13]='derp'}

for i, v in ipairs(t) do
    print(i)
end

The output is the same, it only goes through and prints 1. If you use just pairs on the other hand you get an output of 1, 7, and 13.

t={[1]='derp1', [7]='derp2', [13]='derp3'}

for i, v in ipairs(t) do
    print(i..':'..v)
end
-- Only outputs '1:derp1'

for i, v in pairs(t) do
    print(i..':'..v)
end
-- Outputs (1:derp1, 13:derp3, 7:derp2)
Ad
Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

ipairs loops through the table in a numerical order in increments of one, then stops when it reaches nil. think of it like this:

for i=1, math.huge do
    if t[i] == nil then break end
end

pairs finds all non-nil values in a table, and works with dictionaries. it returns next, table which is why it is the same as using next directly.

pairs:

for i, v in pairs(tab) do
    print(v)
end

next:

for i, v in next, tab do
    print(v)
end
0
Okay...so does it matter which one I use with GetChildren()? jamesarsenault 192 — 7y
0
no, not really. numerical is faster than next, next is faster than ipairs, ipairs is faster than pairs Disillusions 61 — 7y

Answer this question