如何按照他们的"分数"对Lua中的内部表进行排序然后"索引"?

时间:2017-09-08 13:46:33

标签: sorting lua lua-table

我在变量T中存储了以下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表排序?

2 个答案:

答案 0 :(得分:1)

在lua中,表包含两个数据结构:数组和字典。

排序意味着排序数组,其中每个元素与数字索引相关联,索引是连续的,即:1,2,3 ......

您的初始表实际上是一个字典 - 每个条目都有一个与之关联的任意键(在您的情况下,这些是字符串)。

因此,您所描述的实际上并不是一个排序任务,您最终想要一种不同类型的表。

table.sort适用于lua表的数组部分,即那些索引从1开始并以第一个nil条目结束的元素。

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循环遍历表并同时添加新元素是不明智的。因此,惯用的方式仍然涉及中间复制。

答案 1 :(得分:1)

您需要首先将您拥有的哈希转换为表,然后使用自定义排序函数对该表的元素进行排序,该函数按score(降序)排序,然后按{{1}排序对于那些得分相同的元素,(升序)。

这样的事情应该有效:

index