原文:http://rangercyh.blog.51cto.com/1444712/1032925
tbtest = {
[1] = 1,
[10000] = 2,
}
local count = 0
for i=1, table.maxn(tbtest) do
count = count + 1
print(tbtest[i])
end
print(count)
你会看到打印结果是多么的坑爹,只有1和10000是有意义的,其他的全是nil,而且count是10000。耗时非常久。一般我不这么遍历。但是有一种情况下又必须这么遍历,这个在我的工作中还真的遇到了,这是后话,等讲完了再谈。
function pairsByKeys(t)
local a = {}
for n in pairs(t) do
a[#a+1] = n
end
table.sort(a)
local i = 0
return function()
i = i + 1
return a[i], t[a[i]]
end
end
然后在遍历的时候使用这个迭代器就可以了,table同上,遍历如下:
for key, value in pairsByKeys(tbtestAward) do
if nSeq <= key then
return key
end
end