先看看官方手册的说明吧:

复制代码 代码如下:
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也没问题。

以上(为什么不少回答会以「以上」收尾?,这里就是结束的意思吧)

标签:
Lua,ipair,pair

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“Lua中ipair和pair的区别”

暂无“Lua中ipair和pair的区别”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。