The difference between ipairs and pairs when Lua generic for traverses table
![The difference between ipairs and pairs when Lua generic for traverses table The difference between ipairs and pairs when Lua generic for traverses table](http://up-free-imgs.azimiao.com/wp-content/uploads/2017/11/lua.jpg)
Meow - Introduction
for i,v in ipairs(tableName) do print(i,v); end for k,v in pairs(tableName) do print(k,v); end
Try pears
--'Pure array' testTab ={1,2,3,4,5}; --'Pure table' testTab1 = {a = 1, b = 2, c =3}; --'Miscellaneous table 1' testTab2 = {"zi", a = 5,b = 10, c = 15, "miao","chumo"}; --'Miscellaneous table 2' testTab3 = {"zi", a = 5,b = 10, c = 15, "miao",nil,"chumo"};
Ipairs and pairs traverse pure arrays
for i,v in ipairs(tableName) do Print ("ipairs traverses pure arrays"); for i,v in ipairs(testTab) do print(i,v); end Print ("pairs traverse pure array"); for k,v in pairs(testTab) do print(k,v); end
for i,v in ipairs(tableName) do Ipairs traverses pure array 1 1 2 2 3 3 4 4 5 5 Pairs traverses a pure array 1 1 2 2 3 3 4 4 5 5
Ipairs and pairs traverse pure tables
for i,v in ipairs(tableName) do Print ("ipairs traverses pure tables"); for i,v in ipairs(testTab1) do print(i,v); end Print ("pairs traverse pure tables"); for k,v in pairs(testTab1) do print(k,v); end
for i,v in ipairs(tableName) do Ipairs traverses pure table Pair traverses the pure table c 3 a 1 b 2
Ipairs and pairs traverse miscellaneous table 1
for i,v in ipairs(tableName) do Print ("ipairs traverse miscellaneous table 1"); for i,v in ipairs(testTab2) do print(i,v); end Print ("pairs traverse miscellaneous table 1"); for k,v in pairs(testTab2) do print(k,v); end
for i,v in ipairs(tableName) do Ipairs traversal miscellaneous table 1 1 zi 2 miao 3 chumo Pairs traverses miscellaneous table 1 1 zi 2 miao 3 chumo b 10 c 15 a 5
Ipairs and pairs traverse miscellaneous table 2
for i,v in ipairs(tableName) do Print ("ipairs traverse miscellaneous table 2"); for i,v in ipairs(testTab3) do print(i,v); end Print ("pairs traverse miscellaneous table 2"); for k,v in pairs(testTab3) do print(k,v); end
Ipairs traversal miscellaneous table 2 1 zi 2 miao Pairs traverses miscellaneous table 2 1 zi 2 miao 4 chumo a 5 c 15 b 10
Analysis and summary
This is because table stores values in order, but it stores key value pairs according to the hash value of the key, not in alphabetical or numerical order.
For a, if you execute print (a [3]), the output will also be Good. That is to say, table does not give an index value to the key value.
That is to say, ipairs only prints the data with index values in the table in the order of index values, and does not care about the data without index values.
The pairs print according to the index value first, and then print its value according to the hash value of the key value pair after printing.
http://blog.csdn.net/tsbyj/article/details/47302611
References