永发信息网

days = {"1","2","3","4","5"} for _, v in pairs(day

答案:1  悬赏:40  手机版
解决时间 2021-04-04 05:25
  • 提问者网友:我一贱你就笑
  • 2021-04-03 23:51
days = {"1","2","3","4","5"} for _, v in pairs(days) do 与 for i,v in ipairs(days) do的区别在哪里?
最佳答案
  • 五星知识达人网友:举杯邀酒敬孤独
  • 2021-04-04 01:29
先看看官方手册的说明吧:
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.

ipairs (t)If t has a metamethod __ipairs, calls it with t as argument and returns the first three results from the call.
Otherwise, 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会遍历table的所有键值对。如果你看过耗子叔的Lua简明教程,你知道table就是键值对的数据结构。
而ipairs就是固定地从key值1开始,下次key累加1进行遍历,如果key对应的value不存在,就停止遍历。顺便说下,记忆也很简单,带i的就是根据integer key值从1开始遍历的。

请看个例子。
tb = {"oh", [3] = "god", "my", [5] = "hello", [6] = "world"}

for k,v in ipairs(tb) do
print(k, v)
end
输出结果就是:
1 oh
2 my
3 god
因为tb不存在tb[4],所以遍历到此为止了。

for k,v in pairs(tb) do
print(k, v)
end
输出结果:
1 oh
2 my
3 god
6 world
5 hello
我们都能猜到,将输出所有的内容。然而你发现输出的顺序跟你tb中的顺序不同。
如果我们要按顺序输出怎么办?办法之一是:
for i = 1, #tb do
if tb[i] then
print(tb[i])
else
end
当然,仅仅是个数组的话,ipairs也没问题。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯