Quick-cocos2dx,中关于table条件排序

来源:互联网 发布:数据库面试宝典 编辑:程序博客网 时间:2024/06/02 03:23

最近公司要求对任务列表进行排,任务有三种状态(status)0:未完成,1:已完成(可以领取),2:已经领取。

table有个sort函数: table.sort(table,comp),其中comp是比较函数,接收两个参数(依次为a,b),并返回一个布尔值,当a排在b前面时,返回true,反之返回false。

例如:

tb1 ={"apple","cat","dog","boy"};

sorFunc =  function(a,b) return b<a end;

table.sort (tb1,sorFunc);

print(table.concat(tb1,",");

        apple,boy,cat,dog

升级拓展,多个条件排序:

      team = {}

      team.insert(team,{name = "Bobo",age =10, birthDay=3 })

      team.insert(team,{name = "Anna",age =12, birthDay=3 })

      team.insert(team,{name = "Candy",age =10, birthDay=4 })

      如果对这个table排序:按照年龄升级排序,在年龄相同时,按照姓名排序

可以这样写:

    function sortAgeName(a,b)

if a.age == b.age then

return a.age<b.age

else 

return a.name<b.nan

        end

  end


--------------------------------------------------------------------

          但是以上排序方法无法满足策划需求,status = 1 排在最前面,status =1在中间,status =0在最后的需求,因此需要自己写一个排序,


function TaskListInfo:getTaskTable()

local count = 0;

for k,v in pairs(self.type1) do   --排序type1这个表
if v.status == 1 then --插入到最前面
table.insert(s_type1,1,v);
count = count + 1;
elseif v.status == 2 then
table.insert(s_type1,v); --插入到末尾

elseif v.status ==0 then 
table.insert(s_type1,count+1,v)
end
end

return s_type1

end

        s_type1 即是我们返回的根据此要求排序的table。

        不知道大家还有什么好的方案?





原创粉丝点击