lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

I was experimenting with table constructors and saw some unexpected behaviour.
The code below initializes a table in 3 different ways.

t1 = { 10, 20, 30, 40 }
print( "--- t1 ipairs ---" )
for k, v in ipairs( t1 ) do print( k, v ) end
print( "--- t1 pairs ---" )
for k, v in pairs( t1 ) do print( k, v ) end

t2 = { 10, 20, [3] = 30, 40 }
print( "--- t2 ipairs --" )
for k, v in ipairs( t2 ) do print( k, v ) end
print( "--- t2 pairs ---" )
for k, v in pairs( t2 ) do print( k, v ) end

t3 = { [1] = 10, [2] = 20, [3] = 30, [4] = 40 }
print( "--- t3 ipairs ---" )
for k, v in ipairs( t3 ) do print( k, v ) end
print( "--- t3 pairs ---" )
for k, v in pairs( t3 ) do print( k, v ) end

The following output was generated when I execute it with Lua 5.4.1;

--- t1 ipairs ---
1       10
2       20
3       30
4       40
--- t1 pairs ---
1       10
2       20
3       30
4       40
--- t2 ipairs --
1       10
2       20
3       40
--- t2 pairs ---
1       10
2       20
3       40
--- t3 ipairs ---
1       10
2       20
3       30
4       40
--- t3 pairs ---
4       40
1       10
2       20
3       30


I expected that 't2' and 't3' are equivalent to 't1' but the output differs.
Especially the contents of 't2' is odd.

't3' behaves according to the documentation but the items seems to go into the hash part of the table.
However, the way how items are stored in a table is an implementation detail.

What behaviour for 't2' (and 't3') should I expect?

-- Jasper