I was just wondering how do I use these to functions
How To Use Pairs And Ipairs
Started by jay5476, Aug 07 2013 12:54 AM
1 reply to this topic
#1
Posted 07 August 2013 - 12:54 AM
#2
Posted 07 August 2013 - 06: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.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users











