Lua 5.2 reorders items in a table

In lua 5.1 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 performance)

 LD1 LD2 LD3 LD4 I1 I2 I3 

(second performance)

 LD1 LD2 LD3 LD4 I1 I2 I3 

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

(first performance)

 I1 I2 LD4 I3 LD1 LD2 LD3 

(second performance)

 LD2 LD3 LD4 I3 I1 I2 LD1 

Why does this error occur when I use lua 5.2?

+4
source share
3 answers

In Lua 5.2.1, seed randomization for hashing was introduced.

+5
source

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

The order in which indexes are listed is not indicated even for numeric indexes.

Please note that many hash structures of many programming languages ​​(which are Lua tables) do not guarantee any specific (introductory) order of their values.

In other words: this is not a mistake. You should not expect any particular order of inserted elements in a table. The only order you can expect is when you use numbers as keys and use the ipairs function, which will ipairs over pairs ( 1,t[1] ), ( 2,t[2] ), ... , up to The first integer key that is not in the table.

+5
source

Elements of the table are not specified.

You will need to create a table that maps numerical indices to a specific subtable in sums . You can even use the sums table to store both your sub-stats and your order for them.

For instance:

 -- 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 
+4
source

All Articles