1. table中不能有nil
table.sort是排序函数,它要求要排序的目标table的必须是从1到n连续的,即中间不能有nil。
2. 重写的比较函数,两个值相等时不能return true
此外,当比较函数没有写的时候,table.sort默认按照lua里面的排序规则升序排序;
当额外写了比较函数时,相当于用你额外写的比较函数重载了lua中自带的“<”操作符。
这就有一个特别要注意的问题,当两个数相等的时候,比较函数一定要返回false!
如果两个值相等都,
排序函数返回true
时则会报错 invalid order function for sorting
local testTb = {4,45,45,43,55,3}
table.sort(
testTb,
function(c1, c2)
if c1 == c2 then
return false;
end
if not c1 or not c2 then
return false
end
return c1 < c2
end
)