Lua sort

首先,我们来看一下官方的文档:
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就可以了,因为小于的相反是大于等于,包含等于,就不会有问题了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值