Lua 多条件排序

最近在游戏里做个活动,用到了table.sort()方法,为加深印象,就顺便记下来,有不足之处,请多多指教。
以下是从服务端下发的礼包数据:
info_list = {
[1] = {state = 1, id = 1, did_num = 40, target_num = 20},
[2] = {state = 1, id = 2, did_num = 69, target_num = 10},
[3] = {state = 0, id = 3, did_num = 1, target_num = 6},
[4] = {state = 0, id = 4, did_num = 0, target_num = 6},
[5] = {state = 0, id = 5, did_num = 0, target_num = 6},
[6] = {state = 0, id = 6, did_num = 0, target_num = 6},
[7] = {state = 0, id = 7, did_num = 0, target_num = 5},
[8] = {state = 0, id = 8, did_num = 0, target_num = 10},
[9] = {state = 0, id = 9, did_num = 0, target_num = 150},
[10] = {state = 0, id = 10, did_num = 0, target_num = 5},
[11] = {state = 1, id = 11, did_num = 15, target_num = 10},
[12] = {state = 0, id = 12, did_num = 0, target_num = 5},
[13] = {state = 0, id = 13, did_num = 0, target_num = 10},
[14] = {state = 0, id = 14, did_num = 0, target_num = 10},
[15] = {state = 0, id = 15, did_num = 0, target_num = 10},
[16] = {state = 0, id = 16, did_num = 0, target_num = 30},
[17] = {state = 0, id = 17, did_num = 0, target_num = 30},
[18] = {state = 0, id = 18, did_num = 0, target_num = 20},
[19] = {state = 0, id = 19, did_num = 0, target_num = 6},
[20] = {state = 0, id = 20, did_num = 5, target_num = 10},
[21] = {state = 0, id = 21, did_num = 5, target_num = 30},
[22] = {state = 0, id = 22, did_num = 0, target_num = 1},
[23] = {state = 0, id = 23, did_num = 0, target_num = 1},
}
说明:state=0表示礼包未领取,state=0表示已领取,id就是对应的活动id,did_num当前完成次数,target_num目标次数。

要求:已领取的礼包放到最后,可领取礼包置顶,任务完成越多越靠前,其他按id来排序。

–按state从小到大排序,若state相等按任务完成百分比从大到小排序,若百分比相同,按id小到大排序
function sortFunc(a, b)
if a.state == b.state then
if a.did_num/a.target_num == b.did_num/b.target_num then
return a.id < b.id
else
return a.did_num/a.target_num*100 > b.did_num/b.target_num*100
end
else
return a.state < b.state
end
end
table.sort(info_list, sortFunc)

for k=1, #qixiInfo_list do
print(“—–”, k, qixiInfo_list[k].state, qixiInfo_list[k].id, qixiInfo_list[k].did_num, qixiInfo_list[k].target_num)
end

打印结果如下:
—– 1 0 20 5 10
—– 2 0 3 1 6
—– 3 0 21 5 30
—– 4 0 4 0 6
—– 5 0 5 0 6
—– 6 0 6 0 6
—– 7 0 7 0 5
—– 8 0 8 0 10
—– 9 0 9 0 150
—– 10 0 10 0 5
—– 11 0 12 0 5
—– 12 0 13 0 10
—– 13 0 14 0 10
—– 14 0 15 0 10
—– 15 0 16 0 30
—– 16 0 17 0 30
—– 17 0 18 0 20
—– 18 0 19 0 6
—– 19 0 22 0 1
—– 20 0 23 0 1
—– 21 1 2 69 10
—– 22 1 1 40 20
—– 23 1 11 15 10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值