Not pairs, ipairs. Why does it exist? What can you do with it?
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.
1 | t = { 1 , 2 , 3 , nil , 4 } |
2 | for i,v in ipairs (t) do |
3 | print (v) |
4 | end |
5 |
6 | --1, 2, 3 |
7 | --It stops at 3, beacuse nil is not a number |
Another example:
1 | t = { "string1" , "string2" , "string3" , fourthvalue = "string4" } |
2 | for i,v in ipairs (t) do |
3 | print (v) |
4 | end |
5 |
6 | --string1, string2, string3 |
7 | --It stops at the fourth value, because it's a variable and not a string |
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.
ipairs
and 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.
1 | tab = { "#1" , "#2" , nil , "#3" } |
2 | for i,v in ipairs (tab) do |
3 | print (i,v) |
4 | end |
5 |
6 | -- this prints > 1 #1 , 2 #2. But doesn't go past the `nil` |
1 | tab = { "#1" , "#2" , nil , "#3" } |
2 | for i,v in pairs (tab) do |
3 | print (i,v) |
4 | end |
5 |
6 | -- this prints > 1 #1 , 2 #2 , 4 #3. But does go past the `nil` |