This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
macss_'s profile picture

in pairs and ipairs work

Started by macss_, 19 May 2014 - 11:29 PM
macss_ #1
Posted 20 May 2014 - 01:29 AM
I was looking out some codes and I keep seeing (is it right?) the:


for i, v in pairs do
   do something
end

As well as the ipairs, and I seem not to understand it correctly, i read about it but can't figure out correctly, could someone please explain me how this thing works, and what I could use it for?
KingofGamesYami #2
Posted 20 May 2014 - 04:08 AM

words = {hello, world}
for k, v in pairs(words) do
 print(v)
end
result:

hello
world
Additionally, loaded apis can be iterated through

for k, v in pairs( turtle ) do
 print( k.." : "..v )
end
result:

craft : --#random function pointer thing, 0x204fv25 whatever
forward : --#more function pointer things
--#etc.

additionally, you could use this with anything that returns values

for word in string.gmatch("hello world", "%A+") do
 print(word)
end
result:

hello
world
Dog #3
Posted 20 May 2014 - 05:44 AM
If I understand correctly, ipairs returns all integer keys (and their associated values) in numeric order. pairs doesn't necessarily return them in order.

Here are a couple of references (originally provided by theoriginalbit)

Tables Tutorial

For Tutorial