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