我有一个我想要排序的Lua表。表的格式如下:
tableOfKills[PlayerName] = NumberOfKills
这意味着,例如,如果我有一个名为Robin的玩家总共有8个杀戮而另一个名为Jon的玩家共有10个杀戮,那么该表将是:
tableOfKills[Robin] = 8
tableOfKills[Jon] = 10
我如何对这种类型的表进行排序以首先显示最高的杀戮?提前谢谢!
答案 0 :(得分:79)
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