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

How To Use Pairs And Ipairs

Started by jay5476, 06 August 2013 - 11:54 PM
jay5476 #1
Posted 07 August 2013 - 01:54 AM
I was just wondering how do I use these to functions
GamerNebulae #2
Posted 07 August 2013 - 07:04 AM
There is one big difference between pairs and ipairs (as far as I know). The main difference is, that ipairs is made for tables that start with a number. It's kinda like table.sort, but then for numbers. It makes sure it prints out a table in order. I'll give you an example.


table = {}
table[1] = "foo"
table[2] = "bar"
--# To print the loop, I'll give you two examples using pairs and ipairs
for i,j in pairs(table) do --# This will iterate through the table
  print(i..": "..j) --# This will give the results you got from the table
end
--# Now you might be thinking it would be logical to get this:
1: foo
2: bar
-# But without the use of ipairs, you could get this as well:
2: bar
1: foo
--# By using ipairs you will always get the right order with numbers, but if the index is a string, don't use it. The index is this thing ["foo"].
table = {}
table["foo"] = "bar"
table["foobar"] = 123
for i,j in ipairs(table) do
  print(i..": "..j)
end
--# This will give you no results, because the index is a string.