Saulo Cabral
Saulo Cabral

Reputation: 113

lua 5.2 changes the order of elements in the table

In lua 5.1 the code:

sums = { 
    ["LD1"] = { }, 
    ["LD2"] = { }, 
    ["LD3"] = { }, 
    ["LD4"] = { }, 
    ["I1"] = { }, 
    ["I2"] = { }, 
    ["I3"] = { }
}

for fld = 1, 22, 1 do
    table.insert( sums["LD1"] , 0 );
    table.insert( sums["LD2"] , 0 );
    table.insert( sums["LD3"] , 0 );
    table.insert( sums["LD4"] , 0 );
    table.insert( sums["I1"] , 0 );
    table.insert( sums["I2"] , 0 );
    table.insert( sums["I3"] , 0 );
end

for i,O in pairs(sums) do
    print(i)
end

Shows the sequence:

(first execution)

LD1
LD2
LD3
LD4
I1
I2
I3

(second execution)

LD1
LD2
LD3
LD4
I1
I2
I3

In lua 5.2, the sequence is presented in random order:

(first execution)

I1
I2
LD4
I3
LD1
LD2
LD3

(second execution)

LD2
LD3
LD4
I3
I1
I2
LD1

why this error happens when I use lua 5.2?

Upvotes: 5

Views: 1741

Answers (3)

lhf
lhf

Reputation: 72312

Lua 5.2.1 introduced some randomization of seeds for hashing.

Upvotes: 5

Mud
Mud

Reputation: 28991

There is no specified order to the elements of a table.

You'll need to create a table that maps numerical indexes to a particular subtable in sums. You can even use the sums table to hold both your subtables and your ordering for them.

For example:

-- create table with sum ids in a specific order
sums = { "LD1", "LD2", "LD3", "LD4", "I1", "I2", "I3" }

-- create subtables in sums for each id
for i,id in ipairs(sums) do
    sums[id] = {}
end

-- stick some data in the sum tables
for fld = 1, 22 do
    table.insert( sums["LD1"] , 0 );
    table.insert( sums["LD2"] , 0 );
    table.insert( sums["LD3"] , 0 );
    table.insert( sums["LD4"] , 0 );
    table.insert( sums["I1"] , 0 );
    table.insert( sums["I2"] , 0 );
    table.insert( sums["I3"] , 0 );
end

-- show sum tables in order
for i,id in ipairs(sums) do
    print(id, sums[id])
end

Upvotes: 5

Bart Kiers
Bart Kiers

Reputation: 170148

Both Lua 5.1 and 5.2 mention the following in the next function (which the pairs function uses):

The order in which the indices are enumerated is not specified, even for numeric indices.

Note that many programming languages' hash-based structures (which Lua tables are) don't guarantee any specific (insertion) order of their values.

In other words: this is not error. You shouldn't expect any specific order of the inserted elements in your table. The only order you can expect is when you're using numbers as keys, and use the ipairs function which will iterate over the pairs (1,t[1]), (2,t[2]), ..., up to the first integer key absent from the table.

Upvotes: 5

Related Questions