lua中函数注意事项

table.sort()
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 order may 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就可以了,因为小于的相反是大于等于,包含等于,就不会有问题了。


标准库提供了集中迭代器,包括迭代文件每行的(io.lines),迭代table元素的(pairs),迭代数组元素的(ipairs),迭代字符串中单词的 

(string.gmatch)等等。LUA手册中对与pairs,ipairs解释如下:

ipairs (t)

Returns three values: an iterator function, the table t, and 0, so that the construction

for i,v in ipairs(t) do body end

will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.

 

 

 

 

pairs (t)

Returns three values: the next function, the table t, and nil, so that the construction

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

 

这样就可以看出  ipairs以及pairs 的不同。

 

pairs可以遍历表中所有的key,并且除了迭代器本身以及遍历表本身还可以返回nil;

 

但是ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。它只能遍历到表中出现的第一个不是整数的key



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值