簡體   English   中英

在 Lua 中對 Table[] 進行排序

[英]Sort a Table[] in Lua

我有一個要排序的 Lua 表。 表格格式如下:

tableOfKills[PlayerName] = NumberOfKills

這意味着,例如,如果我有一個名叫 Robin 的玩家總共擊殺了 8 次,另一個名叫 Jon 的玩家總共擊殺了 10 次,那么表格將是:

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

我將如何對這種類型的表格進行排序以首先顯示最高擊殺數? 提前致謝!

Lua中的表是一組具有唯一鍵的鍵值映射。 這些對以任意順序存儲,因此表不以任何方式排序。

你可以做的是遍歷以某種順序表。 基本pairs不能保證訪問密鑰的順序。 這是一個自定義版本的pairs ,我稱之為spairs因為它按排序順序遍歷表:

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

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

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

避免迭代器等的另一種排序方法是將表傳遞給鍵值對列表(即:list = {{k1,v1}, {k2, v2}, ...}。這是我的解決方案:

local ranks = {}
for player,kills in pairs(tableOfKills) do
    table.insert(ranks, {player, kills})
end

-- Now we use Lua's built-in sort function with a short custom comparator function:
table.sort(ranks, function (a, b) return a[2] > b[2] end)

-- The only thing left to do is display the results:
for i=1,#ranks do
    print(ranks[i][1], ranks[i][2])
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM