Lua - 按字符串对 Table 进行排序
Lua - Sorting a Table by String
我已经为我的计分板制作了一个 LUA table:
Score.Ranks = {}
Score.Ranks["superadmin"] = {name = "Boss", col = Color(183, 109, 253) }
Score.Ranks["operator"] = {name = "Chief", col = Color(254, 129, 1) }
Score.Ranks["commander"] = {name = "Commander", col = Color(222, 54, 54) }
Score.Ranks["moderator"] = {name = "Director", col = Color(53, 225, 227) }
我想对这个 Table 进行排序,以便 'names' 在我的记分牌上显示时按以下顺序排序:
Boss
Director
Commander
Chief
我该怎么做?
因为您只有 4 件商品,所以我会手动将它们分类。
print("Scoreboard:")
print(Score.Ranks.superadmin.name)
print(Score.Ranks.moderator.name)
print(Score.Ranks.commander.name)
print(Score.Ranks.operator.name)
您必须告诉您的计算机超级管理员排在版主之前,以便稍后对其进行排序。但是,如果您无论如何都必须为每个条目输入优先级,则无需排序。这并不是说您可以从任何 属性.
派生出订单
你只能用数字索引对 table 进行排序,所以首先转换 table:
Score.Ranks = {}
Score.Ranks["operator"] = {name = "Chief", col = Color(254, 129, 1) }
Score.Ranks["superadmin"] = {name = "Boss", col = Color(183, 109, 253) }
Score.Ranks["commander"] = {name = "Commander", col = Color(222, 54, 54) }
Score.Ranks["moderator"] = {name = "Director", col = Color(53, 225, 227) }
local tmp_t = {}
for k,v in pairs(Score.Ranks) do
local rank = (k=="superadmin") and 1 or (k=="operator" and 3 or 2)
table.insert(tmp_t, { rank = rank .. v.name, key = k, name = v.name, col = v.col} )
end
然后table按名字排序然后使用
table.sort(tmp_t , function (a, b) return (a.rank < b.rank ) end)
for k,v in pairs(tmp_t) do
print(k , v.rank, v.key, v.name)
end
我已经为我的计分板制作了一个 LUA table:
Score.Ranks = {}
Score.Ranks["superadmin"] = {name = "Boss", col = Color(183, 109, 253) }
Score.Ranks["operator"] = {name = "Chief", col = Color(254, 129, 1) }
Score.Ranks["commander"] = {name = "Commander", col = Color(222, 54, 54) }
Score.Ranks["moderator"] = {name = "Director", col = Color(53, 225, 227) }
我想对这个 Table 进行排序,以便 'names' 在我的记分牌上显示时按以下顺序排序:
Boss
Director
Commander
Chief
我该怎么做?
因为您只有 4 件商品,所以我会手动将它们分类。
print("Scoreboard:")
print(Score.Ranks.superadmin.name)
print(Score.Ranks.moderator.name)
print(Score.Ranks.commander.name)
print(Score.Ranks.operator.name)
您必须告诉您的计算机超级管理员排在版主之前,以便稍后对其进行排序。但是,如果您无论如何都必须为每个条目输入优先级,则无需排序。这并不是说您可以从任何 属性.
派生出订单你只能用数字索引对 table 进行排序,所以首先转换 table:
Score.Ranks = {}
Score.Ranks["operator"] = {name = "Chief", col = Color(254, 129, 1) }
Score.Ranks["superadmin"] = {name = "Boss", col = Color(183, 109, 253) }
Score.Ranks["commander"] = {name = "Commander", col = Color(222, 54, 54) }
Score.Ranks["moderator"] = {name = "Director", col = Color(53, 225, 227) }
local tmp_t = {}
for k,v in pairs(Score.Ranks) do
local rank = (k=="superadmin") and 1 or (k=="operator" and 3 or 2)
table.insert(tmp_t, { rank = rank .. v.name, key = k, name = v.name, col = v.col} )
end
然后table按名字排序然后使用
table.sort(tmp_t , function (a, b) return (a.rank < b.rank ) end)
for k,v in pairs(tmp_t) do
print(k , v.rank, v.key, v.name)
end