• 企业400电话
  • 网络优化推广
  • AI电话机器人
  • 呼叫中心
  • 全 部 栏 目

    网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    Lua中ipair和pair的区别
    POST TIME:2021-10-18 16:57

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

    复制代码 代码如下:

    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脚本语言简明入门教程
    下一篇:Lua教程(一):在C++中嵌入Lua脚本
  • 相关文章
  • 

    关于我们 | 付款方式 | 荣誉资质 | 业务提交 | 代理合作


    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    X

    截屏,微信识别二维码

    微信号:veteran88

    (点击微信号复制,添加好友)

     打开微信