GouDan
GouDan

Reputation: 21

why the pairs in table is different by different init ways

in the 2 example, the table seems do the same things.but the output is different.

local a = {
    [0] = 0,
    [1] = 1,
    [2] = 2,
    [3] = 3,

}
for i, v in pairs(a) do
    print(v)
end

the output is 0 2 3 1

local a = {}
a[0] = 0
a[1] = 1
a[2] = 2
a[3] = 3

for i, v in pairs(a) do
    print(v)
end

the output is 1 2 3 0

it seems like the second example is always output array part first then hash part. but the first example seems like the order is random. why?

Upvotes: 2

Views: 44

Answers (2)

Luatic
Luatic

Reputation: 11191

Not only does pairs not guarantee a specific order, table constructors furthermore don't guarantee a specific order of insertion:

The order of the assignments in a constructor is undefined. (This order would be relevant only when there are repeated keys.)

- the Lua Reference Manual

Therefore, this claim:

the table seems do the same things

is wrong. It might as well be equivalent to:

local a = {}
a[3] = 3
a[2] = 2
a[1] = 1
a[0] = 0

for i, v in pairs(a) do
    print(v)
end

So even if table traversal order is deterministically determined by the insertions - same insertions, same traversal - which wouldb an implementation detail - table constructors may not be read from left to right, line by line - as Lua may shuffle the assignments however it likes.

Furthermore, hashmaps will in practice have to resize and resolve collisions. Lua will be able to avoid at least the resize if you use a table constructor expression; it might theoretically even minimize the effort required to resolve collisions by picking an intelligent insertion order.

Upvotes: 1

Piglet
Piglet

Reputation: 28954

pairs doesn't guarantee a specific order. If you want to have a specific order use a numeric for loop.

for i = 0, 3 do
  print(a[i])
end

Read

http://www.lua.org/manual/5.4/manual.html#pdf-pairs

http://www.lua.org/manual/5.4/manual.html#pdf-next

The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numerical order, use a numerical for.)

Upvotes: 3

Related Questions