2017-09-08 45 views
2

我已經存儲在變量T以下的Lua表:如何通過Lua的「分數」和「索引」對內部表進行排序?

{ 
    ["mn"] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 }, 
    ["kl"] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 }, 
    ["ef"] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 }, 
    ["ab"] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 }, 
    ["cd"] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 }, 
    ["gh"] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 }, 
    ["ij"] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 } 
} 

我要排序的所有T表以下列方式內部表:
1.表具有較高score都放在頂端。
2.等於score的表格按其index排序。

{ 
    [1] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 }, -- highest "score" 
    [2] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 }, 
    [3] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 }, 
    [4] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 }, 
    [5] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 }, -- lowest "score", lowest "index" 
    [6] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 }, -- when scores are the same, sort by their "index" instead 
    [7] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 } -- lowest "score", highest "index" 
} 

如何做到這一點的Lua表排序:

所以,整理後,下面的順序表應在輸出產生的?

+0

https://devdocs.io/lua~5.3/index#pdf-table.sort – hjpotter92

+0

我明白,我必須使用'table.sort' Lua的功能但是,我不知道如何在這種情況下使用它。 – Pojat

回答

1

您需要先將表中的哈希值轉換爲表格,然後使用自定義排序函數對該表格的元素進行排序,該函數按score(降序)排序,然後按index(升序)排序相同的得分。

像這樣的東西應該工作:

local hash = { 
    ["mn"] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 }, 
    ["kl"] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 }, 
    ["ef"] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 }, 
    ["ab"] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 }, 
    ["cd"] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 }, 
    ["gh"] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 }, 
    ["ij"] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 } 
} 
local tbl = {} 
for _,v in pairs(hash) do 
    table.insert(tbl, v) 
end 
table.sort(tbl, function(a,b) 
    return a.score > b.score or a.score == b.score and a.index < b.index 
    end) 
+0

感謝您的幫助! :d – Pojat

1

在lua中,表格包含兩個數據結構:數組和字典。

排序裝置排序陣列,其中每個元件與數字索引和索引相關聯的是連續的是:1,2,3 ...

您初始表實際上是一個字典 - 每個條目有一個任意關鍵的關鍵(在你的情況下,那些是字符串)。

因此,你所描述的實際上並不是一個排序任務,你最終需要一個不同類型的表。

table.sort適用於lua表的數組部分,也就是那些索引從1開始到第一個零結束的元素。

a={s=3,['r']=3, 5,3,2, nil,21} 
       |these| 
       |ones | 

所以,首先要創建一個數組和排序一句:

local sorted={} 
for k,v in pairs(T) do 
    table.insert(sorted,v) 
end 
table.sort(sorted,function(a,b) 
    --your code here 
    --function should return true if element `a` from the array `sorted` 
    --must be higher (to the left of) `b` 
end) 

或者,你可以在條目存儲在無論是在字典和陣列部分相同的表中,table.sort功能會忽略字典。但使用pairs循環表並不明智,並且同時添加新元素。因此,慣用的方式仍然涉及中間複製。

+0

感謝您的解釋。 – Pojat

相關問題