ipairs和pairs的区别

http://blog.csdn.net/bosbear/article/details/6317242

这几天在看LUA,只是记录下自己的一点小小心得。这篇是分析 LUA泛型for中提供的ipairs以及pairs的不同。

 

标准库提供了集中迭代器,包括迭代文件每行的(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

 

下面举个例子吧!

 

 eg:

local tabFiles = {

[3] = "test2",

[6] = "test3",

[4] = "test1"

}

 

for k, v in ipairs(tabFiles) do

print(k, v)

end

 

猜测它的输出结果是什么呢?

 

根据刚才的分析,它在 ipairs(tabFiles) 遍历中,当key=1时候value就是nil,所以直接跳出循环不输出任何值。

 

>lua -e "io.stdout:setvbuf 'no'" "Test.lua"

>Exit code: 0

 

那么,如果是

for k, v in pairs(tabFiles) do

print(k, v)

end

则会输出所有 :
>lua -e "io.stdout:setvbuf 'no'" "Test.lua" 
3 test2
6 test3
4 test1
>Exit code: 0
现在改变一下表内容,
local tabFiles = {
[1] = "test1",
[6] = "test2",
[4] = "test3"
}
for k, v in ipairs(tabFiles) do
print(k, v)
end
现在的输出结果显而易见就是key=1时的value值test1

 >lua -e "io.stdout:setvbuf 'no'" "Test.lua" 

1 test1

>Exit code: 0 

 

好了现在已经说的很清楚啦,以后继续咯~~


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值