Is ipairs reliable on unsorted arrays?

I am wondering if anyone can confirm if you can trust ipairs() to; return all indexes in order, for a table that contains an index but is unsorted.

We have code throughout our project that clones tables using pairs() , however any cloned arrays are returned unordered. I am not sure if this is a problem.

For comparison:

 A = {10, 20, 30, 40, 50, 60} 

in

 B = {[1] = 10, [2] = 20, [3] = 30, [4] = 40, [5] = 50, [6] = 60} 

If you loop them on pairs() , the first is ordered, and the other is not. (On a side note, B unexpectedly sorted if you do a couple of back inserts)

Return to the original question. It seems that B above iterates all the values ​​in order using ipairs() , but is it always guaranteed?

+5
source share
3 answers

Lua table has no order.

This is just a set of non- nil keys, each of which is associated with a single non- nil value.


Implementations optimize the storage of "numeric" keys with positive integer values ​​starting at 1 and ending at the point of their selection, growth and contraction of internal structures using temporary memory compilers for various table operations.

pairs works with all key-value pairs in the table.

ipairs works with a conceptual sequence of adjacent positive integers with 1 and ends just before the first nil value. Other key-value pairs are ignored. So, your answer is “Yes, by design,” as long as your idea of ​​“completing the index” matches.

table.sort does the same. Other key-value pairs are ignored.

The default table length operator ( # ) is more restrictive. It works with “sequence” tables, which are tables without “numeric” keys with positive integer values ​​(empty sequence) or all of their “numeric” keys with positive integer values ​​are a continuous sequence starting from 1. If you use the length operator default tables for inconsistency, you get undefined behavior.

+3
source

Yes it will.

ipairs() will continuously repeat from index 1 to n and split the first index, which is not continuous.

For instance:

 B = {[1] = 10, [2] = 20, [3] = 30, [4] = 40, [5] = 50, [6] = 60} for i,v in ipairs(B) do print(i,v) end will print: 1 10 2 20 3 30 4 40 5 50 6 60 

But,

 B = {[1] = 10, [2] = 20, [3] = 30, [5] = 40, [6] = 50, [7] = 60} for i,v in ipairs(B) do print(i,v) end will print 1 10 2 20 3 30 

Because 1,2,3 constant, but break 4 , so ipairs stop.

+4
source

Yes, he guaranteed that ipairs orders the table with integer keys from 1 in order. Regardless of whether the table is sorted, it does not matter.

From the Reference Guide: ipairs :

 for i,v in ipairs(t) do body end 

will iterate over pairs ( 1 , t[1] ), ( 2 , t[2] ), ... up to the first integer key that is not in the table.

+3
source

Source: https://habr.com/ru/post/1209461/


All Articles