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  
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值