Lua -- pairs和ipairs区别

Lua官方文档:http://www.lua.org/docs.html

标准库提供了集中迭代器,包括迭代文件每行的(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 key–value pairs (1,t[1]), (2,t[2]), …, up to the first nil value.
遍历到表中第一个不是整数的key,但是ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。

pairs (t)
If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.
Otherwise, 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.
遍历表中的所有key,并且除了迭代器本身以及遍历表本身还可以返回nil。

eg:

tab = {
    [2] = "tab1",
    [3] = "tab2",
    [5] = "tab3"
}
for k, v in ipairs(tab) do
    print(k,v)
end

猜测它会输出什么结果呢?
根据文档分析,它在ipairs(tab)遍历中,当key = 1时候value就是nil,所以它会直接跳出循环,不输出任何值。
如果是:

for k, v in pairs(tab) do
    print(k,v)
end

他会输出:

2   tab1
3   tab2
5   tab3

改变一些表中的内容

tab = {
    [1] = "tab1",
    [3] = "tab2",
    [5] = "tab3"
}
print("ipairs:")
for k, v in ipairs(tab) do
    print(k,v)
end
print("pairs:")
for k, v in pairs(tab) do
    print(k,v)
end

输出结果显而易见了:

ipairs:
1   tab1
pairs:
1   tab1
5   tab3
3   tab2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值