如何对这个lua表进行排序? [英] How to sort this lua table?

查看:39
本文介绍了如何对这个lua表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个结构

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

我需要按优先级DESC对该表进行排序,其他值无关紧要.例如.首先是Healthbar,然后是Powerbar,然后再进行其他所有操作.

I need to sort this table by priorty DESC, other values does not matter. E.g. Healthbar first, then Powerbar, and then going all others.

//编辑.

密钥必须保留.

//编辑#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

推荐答案

您无法对记录表进行排序,因为条目是由Lua内部排序的,并且您无法更改顺序.

You can't sort a records table because entries are ordered internally by Lua and you can't change the order.

一种替代方法是创建一个数组,其中每个条目都是一个包含两个字段( name priority )的表,然后对该表进行排序,如下所示:

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

输出:

1       Healthbar       40
2       Powerbar        35
3       Announcements   0

这篇关于如何对这个lua表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆