Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 708
Saulo Cabral Avatar asked Dec 08 '22 22:12

Saulo Cabral


2 Answers

Lua 5.2.1 introduced some randomization of seeds for hashing.

like image 57
lhf Avatar answered Jan 18 '23 12:01

lhf


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.

like image 24
Bart Kiers Avatar answered Jan 18 '23 12:01

Bart Kiers