Lua实战之布尔值(boolean)排序
Description
将 targetTbl 按 bValue 进行排序(true > false),bValue 相同则按 id 进行顺序(由小到大)排序!
local targetTbl = {
{id = 1, bValue = false},
{id = 2, bValue = true},
{id = 3, bValue = true},
{id = 4, bValue = false},
{id = 5, bValue = true}
}
Implemention
table.sort(targetTbl, function(a, b)
if a.bValue == b.bValue then
return a.id < b.id
end
return a.bValue
end)
for _, data in pairs(targetTbl) do
print(data.id, data.bValue)
end
--[[
2 true
3 true
5 true
1 false
4 false
]]
Expansion
没有稳定排序的条件,以布尔值 bValue 为最终排序依据进行排序!
true > false
table.sort(targetTbl, function(a, b)
return a.bValue and not b.bValue
end)
for _, data in pairs(targetTbl) do
print(data.id, data.bValue)
end
--[[
5 true
2 true
3 true
4 false
1 false
]]
false > true
table.sort(targetTbl, function(a, b)
return not a.bValue and b.bValue
end)
for _, data in pairs(targetTbl) do
print(data.id, data.bValue)
end
--[[
1 false
4 false
3 true
2 true
5 true
]]
ps
运算符优先级:not > and > or