lua 5.2 changes the order of elements in the table

岁酱吖の 提交于 2019-12-23 15:29:43

问题


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?


回答1:


Lua 5.2.1 introduced some randomization of seeds for hashing.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/11974950/lua-5-2-changes-the-order-of-elements-in-the-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!