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

What is ipairs even used for?

Asked by
funyun 958 Moderation Voter
9 years ago

Not pairs, ipairs. Why does it exist? What can you do with it?

3 answers

Log in to vote
1
Answered by 9 years ago

Both are very similar, but pairs will go through a whole mixed table (table with different types of values) while ipairs will stop if there is a change.

t = {1, 2, 3, nil, 4}
for i,v in ipairs(t) do
    print(v)
end

--1, 2, 3
--It stops at 3, beacuse nil is not a number

Another example:

t = {"string1", "string2", "string3", fourthvalue = "string4"}
for i,v in ipairs(t) do
    print(v)
end

--string1, string2, string3
--It stops at the fourth value, because it's a variable and not a string 
0
pairs does the same. SwaggyDuckie 70 — 9y
0
Not exactly. When using pairs, it will skip over nil and print 4 anyways. IcyArticunoX 355 — 9y
Ad
Log in to vote
1
Answered by 9 years ago

I think pairs(t) and ipairs(t) is kind of same. I tried them yesterday, to see diffrence, and I noticed nothing else between them. This can be found at wiki: http://wiki.roblox.com/index.php?title=Function_dump/Basic_functions#ipairs_.28t.29 Only thing I noticed, but I don't know how it affects: ipairs returns 3 values: an iterator function, the table, and 0. pairs returns also 3 values, but diffrent, which are: the next function, the table and nil.

Log in to vote
1
Answered by
woodengop 1134 Moderation Voter
9 years ago

ipairsand pairs are quite similar, it's just that ipairs iterates over the pairs(1,table[1],2 table[2],etc) until it reaches a nil value.

iPairs

tab={"#1","#2",nil,"#3"}
for i,v in ipairs(tab) do
    print(i,v)
end

-- this prints > 1 #1 , 2 #2. But doesn't go past the `nil`

Pairs

tab={"#1","#2",nil,"#3"}
for i,v in pairs(tab) do
    print(i,v)
end

-- this prints > 1 #1 , 2 #2 , 4 #3. But does go past the `nil`

Answer this question