Lua 按不同字段对表进行两次排序

问题描述 投票:0回答:1

下面是我想要排序的示例表结构。

Data = {
    ["C1_RN1::F1"] = {
        ["class"] = "Hunter",
        ["name"] = "C1",
        ["faction"] = "Faction",
        ["race"] = "Human",
        ["realm"] = "RN1",
    },
    ["C2_RN1::F1"] = {
        ["class"] = "Priest",
        ["name"] = "C2",
        ["faction"] = "Faction",
        ["race"] = "Undead",
        ["realm"] = "RN1",
    },
    ["C3_RN1::F1"] = {
        ["class"] = "Hunter",
        ["name"] = "C3",
        ["faction"] = "Faction",
        ["race"] = "Human",
        ["realm"] = "RN1",
    }
}

例如,我想按

race
按字母顺序排序,并按
class
也按字母顺序对所有“人类”种族字符进行排序,并按独立于另一个“种族”的字母顺序对任何其他“种族”进行排序。

我知道如何通过将所有角色名称转储到与

data
表具有相同键的第二个表中进行排序,然后使用
data
和将数据与小于运算符,例如
table.sort
.
    

sorting multidimensional-array lua lua-table
1个回答
0
投票
关联数组

类型的表,它总是具有任意排序的键和值。您只能对类数组表(具有数字索引的表)进行排序。 在您的比较功能中,只需检查您的主要比较是否相等,在这种情况下,您可以继续进行二级比较(然后进行三级比较,等等...)。如果键比较不相等,则返回该键的适当结果(即

data[a].race < data[b].race

<
)。
请注意,

>

并不稳定。

table.sort

local data = {
    ["C1_RN1::F1"] = {
        ["class"] = "Warrior",
        ["name"] = "C1",
        ["faction"] = "Faction",
        ["race"] = "Human",
        ["realm"] = "RN1",
    },
    ["C2_RN1::F1"] = {
        ["class"] = "Priest",
        ["name"] = "C2",
        ["faction"] = "Faction",
        ["race"] = "Undead",
        ["realm"] = "RN1",
    },
    ["C3_RN1::F1"] = {
        ["class"] = "Hunter",
        ["name"] = "C3",
        ["faction"] = "Faction",
        ["race"] = "Human",
        ["realm"] = "RN1",
    }
}

local collapsed = {}

for key, value in pairs(data) do
    table.insert(collapsed, value)
end

table.sort(collapsed, function (a, b)
    if a.race == b.race then
        return a.class < b.class
    end

    return a.race < b.race
end)

for _, character in ipairs(collapsed) do
    print(character.name, character.race, character.class)
end
如果你有很多键要比较,你可以循环遍历它们。

C3 Human Hunter C1 Human Warrior C2 Undead Priest

© www.soinside.com 2019 - 2024. All rights reserved.