• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >Lua > Lua中ipair和pair的区别

Lua中ipair和pair的区别

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了Lua脚本语言简明入门教程等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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

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.
</div>

原来,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</div>
输出结果就是:
1       oh
2       my
3       god
</div>
因为tb不存在tb[4],所以遍历到此为止了。
for k,v in pairs(tb) do
     print(k, v)
end
</div>
输出结果:
1       oh
2       my
3       god
6       world
5       hello
</div>
我们都能猜到,将输出所有的内容。然而你发现输出的顺序跟你tb中的顺序不同。
如果我们要按顺序输出怎么办?办法之一是:
for i = 1, #tb do
     if tb[i] then
          print(tb[i])
     else
end</div>
当然,仅仅是个数组的话,ipairs也没问题。

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

</div>

您可能想查找下面的文章:

相关文章

  • Lua极简入门指南:全局变量
  • Lua中rawset和rawget的作用浅析
  • Lua loadstring函数用法实例
  • Lua中的控制结构(流程控制)简明总结
  • Lua教程(九):元表与元方法详解
  • 把Lua编译进nginx步骤方法
  • Cocos2d-x中调用Lua及HelloWorld.lua源码分解
  • Lua中的metatable介绍
  • Lua教程(十): 全局变量和非全局的环境
  • linux系统安装Nginx Lua环境

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Lua教程(二十):Lua调用C函数
    • Lua和C++的通信流程代码实例
    • Lua中对table排序实例
    • Lua中的metatable详解
    • 详解Lua中的数组概念知识
    • Lua获取系统时间和时间格式化方法及格式化参数
    • Lua中算术运算符的使用示例
    • C语言中调用Lua函数实例
    • Lua的table库函数insert、remove、concat、sort详细介绍
    • Lua中遍历文件操作代码实例

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有