打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
lua 中pairs 和 ipairs区别(转)

目录(?)[+]

标准库提供了集中迭代器,包括迭代文件每行的(io.lines),迭代table元素的(pairs),迭代数组元素的(ipairs),迭代字符串中单词的 

(string.gmatch)等等。LUA手册中对与pairs,ipairs解释如下:

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 (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.

See function next for the caveats of modifying the table during its traversal.

 

这样就可以看出  ipairs以及pairs 的不同。

 

pairs可以遍历表中所有的key,并且除了迭代器本身以及遍历表本身还可以返回nil;

 

但是ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。它只能遍历到表中出现的第一个不是整数的key

 

  1. 下面举个例子吧!  
  2.    
  3.  eg:  
  4. local tabFiles = {  
  5. [3] = "test2",  
  6. [6] = "test3",  
  7. [4] = "test1"  
  8. }  
  9.    
  10. for k, v in ipairs(tabFiles) do  
  11. print(k, v)  
  12. end  
  13.    
  14.    
  15. 猜测它的输出结果是什么呢?  
  16.    
  17. 根据刚才的分析,它在 ipairs(tabFiles) 遍历中,当key=1时候value就是nil,所以直接跳出循环不输出任何值。  
  18.    
  19. >lua -e "io.stdout:setvbuf 'no'" "Test.lua"  
  20. >Exit code: 0  
  21.    
  22. 那么,如果是  
  23. for k, v in pairs(tabFiles) do  
  24. print(k, v)  
  25. end  
  26. 则会输出所有 :  
  27. >lua -e "io.stdout:setvbuf 'no'" "Test.lua"   
  28. 3 test2  
  29. 6 test3  
  30. 4 test1  
  31. >Exit code: 0  
  32. 现在改变一下表内容,  
  33. local tabFiles = {  
  34. [1] = "test1",  
  35. [6] = "test2",  
  36. [4] = "test3"  
  37. }  
  38. for k, v in ipairs(tabFiles) do  
  39. print(k, v)  
  40. end  
  41. 现在的输出结果显而易见就是key=1时的value值test1  
  42.  >lua -e "io.stdout:setvbuf 'no'" "Test.lua"   
  43. 1 test1  
  44. >Exit code: 0   
  45. --[示例1.]--  
  46. local tt =  
  47. {  
  48.     [1] = "test3",  
  49.     [4] = "test4",  
  50.     [5] = "test5"  
  51. }  
  52.   
  53. for i,v in pairs(tt) do        -- 输出 "test4" "test3" "test5"  
  54.     print( tt[i] )  
  55. end  
  56.   
  57. for i,v in ipairs(tt) do    -- 输出 "test3" k=2时断开  
  58.     print( tt[i] )  
  59. end  
  60.   
  61.   
  62.   
  63.   
  64.   
  65. -- [[示例2.]] --  
  66. tbl = {"alpha", "beta", [3] = "uno", ["two"] = "dos"}  
  67.   
  68. for i,v in ipairs(tbl) do    --输出前三个  
  69.     print( tbl[i] )  
  70. end  
  71.   
  72. for i,v in pairs(tbl) do    --全部输出  
  73.     print( tbl[i] )  
  74. end  

http://www.cppblog.com/wc250en007/archive/2011/12/16/162203.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
cnblogs: Lua 中 ipairs 与 pairs 的区别 – perzy 小脚本之家 | 小脚本之家
lua学习笔记 4 迭代法遍历 table,当Table中含Table时,递归输出
Lua中三种循环语句的使用讲解
Lua学习
JAVA|循环和遍历
Lua丨函数中的可变参数(返回多个参数)~arg的用法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服