lua-ipairs, pairs遍历table

1:ua 5.3 手册

http://www.lua.org/manual/5.3/manual.html

2:

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.

 

3:结论

ipairs遍历到第一个key不是interger的元素就会退出,如果你想使用这个特性的话,你应该使用ipairs

pairs无条件遍历整个table

下面上代码,

local tt = {"abc", 123,v = "d", k = nil, "ok", nil, "notok"}

for k, v in ipairs(tt) do
	print(k, "--", v)
end
print("---")
for k, v in pairs(tt) do
	print(k, "--", v)
end
print(tt.k)

print("---spilt---")
tt = {[3] = "a", "b", [2] = "c"}
for k, v in ipairs(tt) do
	print(k, "--", v)
end
print("---")
for k, v in pairs(tt) do
	print(k, "--", v)
end

print("---spilt---")
tt = {[3] = "a", [1] = "b", [2] = "c", "d"}
print(#tt)
for i=1, #tt do
	print(i, tt[i])
end

print("---spilt---")
tt = {[3] = "a", v = "b", [2] = "c"}
print(#tt)
for i=1, #tt do
	print(i, tt[i])
end

从代码的运行结果可以看到,如果键对应的值为Nil,那么pairs也不会遍历到,实际上这里其实只占了一个槽位,但是槽位上是个nil,从notok的键为5可以看出,这里是占用了一个位置的(或者称为占用了一个槽位,还不太清楚)。

ipairs会顺序打印,从索引“1,2,3”,而pairs是乱序的,所以这里其实ipairs更像是一个数组的功能,而pairs更像是一个字典的功能

 

4:next

Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.

 

The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for or the ipairs function.)

 

The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.

 

就两点啊,一点是可以遍历table,这个功能实际和python中是一样,猜测是惰性计算,另外一点是不要在使用next的时候,给一个不存在的key赋值,这可能导致你的table里存在的key的值被修改。(这也太可怕了吧)

 

5:#获取table的长度

它的工作原理是,从索引1开始,直到找不到interger索引为止,所以如果没有索引1,那么#tt的值就是0

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值