简体   繁体   English

如何对这个lua表进行排序?

[英]How to sort this lua table?

I have next structure 我有下一个结构

self.modules = {
    ["Announcements"] = {
        priority = 0,
        -- Tons of other attributes
    },
    ["Healthbar"] = {
        priority = 40,
        -- Tons of other attributes
    },
    ["Powerbar"] = {
        priority = 35,
        -- Tons of other attributes
    },
}

I need to sort this table by priorty DESC, other values does not matter. 我需要通过priorty DESC对此表进行排序,其他值无关紧要。 Eg Healthbar first, then Powerbar, and then going all others. 例如Healthbar,然后是Powerbar,然后去其他所有人。

// edit. //编辑

Keys must be preserved. 必须保留密钥。

// edit #2 //编辑#2

Found a solution, thanks you all. 找到了解决方案,谢谢大家。

local function pairsByPriority(t)
    local registry = {}

    for k, v in pairs(t) do
        tinsert(registry, {k, v.priority})
    end

    tsort(registry, function(a, b) return a[2] > b[2] end)

    local i = 0

    local iter = function()
        i = i + 1

        if (registry[i] ~= nil) then
            return registry[i][1], t[registry[i][1]]
        end

        return nil
    end

    return iter
end

You can't sort a records table because entries are ordered internally by Lua and you can't change the order. 您无法对记录表进行排序,因为Lua在内部对条目进行排序,您无法更改顺序。

An alternative is to create an array where each entry is a table containing two fields ( name and priority ) and sort that table instead something like this: 另一种方法是创建一个数组,其中每个条目都是一个包含两个字段( 名称优先级 )的表,并对该表进行排序,而不是这样:

self.modulesArray = {}

for k,v in pairs(self.modules) do
    v.name = k --Store the key in an entry called "name"
    table.insert(self.modulesArray, v)
end

table.sort(self.modulesArray, function(a,b) return a.priority > b.priority end)

for k,v in ipairs(self.modulesArray) do
    print (k,v.name)
end

Output: 输出:

1       Healthbar       40
2       Powerbar        35
3       Announcements   0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM