在 Lua 中对 Table[] 进行排序 [英] Sort a Table[] in Lua

查看:25
本文介绍了在 Lua 中对 Table[] 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要排序的 Lua 表.表格格式如下:

I have a Lua table that I am trying to sort. The table's format is as follows:

tableOfKills[PlayerName] = NumberOfKills

这意味着,例如,如果我有一个名叫 Robin 的玩家总共击杀了 8 次,另一个名叫 Jon 的玩家总共击杀了 10 次,那么表格将是:

Which means, for example, if I had a player named Robin with a total of 8 kills and another named Jon with a total of 10 kills, the table would be:

tableOfKills[Robin] = 8
tableOfKills[Jon]   = 10

我如何对这种类型的表格进行排序以首先显示最高击杀数?提前致谢!

How would I sort that type of table to show the highest kills first? Thanks in advance!

推荐答案

Lua 中的表是一组具有唯一键的键值映射.这些对以任意顺序存储,因此表格没有以任何方式排序.

A table in Lua is a set of key-value mappings with unique keys. The pairs are stored in arbitrary order and therefore the table is not sorted in any way.

您可以做的是按某种顺序迭代表格.基本的 pairs 不能保证访问密钥的顺序.这是 pairs 的自定义版本,我将其称为 spairs,因为它按排序顺序遍历表:

What you can do is iterate over the table in some order. The basic pairs gives you no guarantee of the order in which the keys are visited. Here is a customized version of pairs, which I called spairs because it iterates over the table in a sorted order:

function spairs(t, order)
    -- collect the keys
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end

    -- if order function given, sort by it by passing the table and keys a, b,
    -- otherwise just sort the keys 
    if order then
        table.sort(keys, function(a,b) return order(t, a, b) end)
    else
        table.sort(keys)
    end

    -- return the iterator function
    local i = 0
    return function()
        i = i + 1
        if keys[i] then
            return keys[i], t[keys[i]]
        end
    end
end

以下是使用此类功能的示例:

Here is an example of use of such function:

HighScore = { Robin = 8, Jon = 10, Max = 11 }

-- basic usage, just sort by the keys
for k,v in spairs(HighScore) do
    print(k,v)
end
--> Jon     10
--> Max     11
--> Robin   8

-- this uses an custom sorting function ordering by score descending
for k,v in spairs(HighScore, function(t,a,b) return t[b] < t[a] end) do
    print(k,v)
end
--> Max     11
--> Jon     10
--> Robin   8

这篇关于在 Lua 中对 Table[] 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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