Lua ipairs、pairs

  先给出 lua 官方 reference 中 ipairs 和 pairs 的解释:

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.

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 有两个返回值,分别是 function 和 table,ipairs 返回三个,前两个和 pairs 一样,最后多返回一个 0.
  我们可以直接在代码里这样使用:

local tab = {
	[0] = 0,
    1,
    2,
    [3] = 3,
    4,
	[4] = 4,
    [8] = 5
}
print("The table is: ", tab)
print("Return value of ipairs:", ipairs(tab))
print("Return value of pairs: ", pairs(tab))

print("\nUsing ipairs:")
for i, v in ipairs(tab) do  print(i, v)  end

print("\nUsing pairs:")
for i, v in pairs(tab)  do  print(i, v)  end

local func, t, idx = ipairs(tab)

print("\nUsing func, t, idx:")
for i, v in func, t, idx do
    print(i,v)
end

local new_tab = {
    "Tom",
    "Jerry"
}

print("\nfunc, new_tab, -1:")
for i, v in func, new_tab, -1 do  print(i, v) end

print("\nfunc, new_tab, 0:")
for i, v in func, new_tab, 0  do  print(i, v) end

print("\nfunc, new_tab, 1:")
for i, v in func, new_tab, 1  do  print(i, v) end

  Lua 中表格的存储可以看 ++待填入链接++,本篇博客关注 ipairs 和 pairs 的区别。
  可以看到,和上边链接中讲到的一样,ipairs 从下标为 1 开始输出,直到当前下标对应值为 nil 为止,pairs 则都输出了
  通过 func,t,idx 获取到 ipairs 的返回值后,可以通过 for i, v in func, t, idx do 这种方式达到同样的遍历效果,下边三种方式是一样的:

for i, v in func, t, idx do
for i, v in func, tab, 0 do
for i, v in ipairs(tab) do

  通过修改第二个参数为新的 table,可以达到遍历新的 table 的目的,通过修改第三个参数 idx,可以达到对初始位置进行偏移的效果,从 -1 开始则什么都不会输出,从 0 开始就和默认的是一模一样的,从 1 开始就会向后偏移一个位置开始输出
  pairs 同理但是没有第三个返回值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值