首先,我们来看一下官方的文档:
table.sort (table [, comp])
Sorts table elements in a given order, in-place,from table[1] to table[n],where n is the length of the table.If comp is given,then it must be a function that receives two table elements,and returns truewhen the first is less than the second(so that not comp(a[i+1],a[i]) will be true after the sort).If compis not given,then the standard Lua operator < is used instead.
The sort algorithm is not stable;that is, elements considered equal by the given ordermay have their relative positions changed by the sort.
下面我来解释以下这段文字的意思
table.sort是排序函数,它要求要排序的目标table的必须是从1到n连续的,即中间不能有nil。
此外,当比较函数没有写的时候,table.sort默认按照lua里面的排序规则升序排序;当额外写了比较函数时,相当于用你额外写的比较函数重载了lua中自带的“<”操作符。这就有一个特别要注意的问题,当两个数相等的时候,比较函数一定要返回false!
举个例子,
a = 5;
b = 5;
c = 5;
d = {a, b, c};
table.sort(d,function(first,senond)
if first < second then
return true;
end
if first > second then
return false;
end
return true;
)
上面那段代码乍一看好像没什么错,可是一执行就会报错了,原因就在于最后的一个true。比较函数执行时,a==b,返回true;b==c,返回true;c==a,返回true。但是,我们所写的比较函数实际上是重载了“小于号”操作符,所以程序执行后的结果就是a<b,b<c,c<a,此时就会出问题!
而我们将高亮的true换成false就可以了,因为小于的相反是大于等于,包含等于,就不会有问题了。