现在的位置: 首页Lua>正文
lua 中 pairs 和 ipairs 的区别
2012年01月30日 Lua 评论数 3 ⁄ 被围观 27,838 次+

luapairsipairs的区别

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. local tabFiles = {   
  2. [3] = "test2",   
  3. [6] = "test3",   
  4. [4] = "test1"  
  5. }   
  6. for k, v in ipairs(tabFiles) do  
  7.     print(k, v)   
  8. end  

猜测它的输出结果是什么呢?根据刚才的分析,它在 ipairs(tabFiles) 遍历中,当key=1时候value就是nil,所以直接跳出循环不输出任何值。

  1. >lua -e "io.stdout:setvbuf 'no'" "test.lua"  
  2. >Exit code: 0  

那么,如果是

  1. for k, v in pairs(tabFiles) do  
  2.     print(k, v)   
  3. end  

则会输出所有:

  1. >lua -e "io.stdout:setvbuf 'no'" "test.lua"    
  2. 3 test2   
  3. 6 test3   
  4. 4 test1   
  5. >Exit code: 0  

现在改变一下表内容,

  1. local tabFiles = {   
  2. [1] = "test1",   
  3. [6] = "test2",   
  4. [4] = "test3"  
  5. }   
  6.   
  7. for k, v in ipairs(tabFiles) do  
  8.     print(k, v)   
  9. end  

现在的输出结果显而易见就是key=1时的value值test1

  1. >lua -e "io.stdout:setvbuf 'no'" "test.lua"    
  2. 1 test1   
  3. >Exit code: 0  
  1. -- [[示例1.]] --   
  2. local tt =   
  3. {   
  4.     [1] = "test3",   
  5.     [4] = "test4",   
  6.     [5] = "test5"  
  7. }   
  8.   
  9. for i,v in pairs(tt) do     -- 输出 "test4" "test3" "test5"  
  10.     print( tt[i] )   
  11. end   
  12.   
  13. for i,v in ipairs(tt) do    -- 输出 "test3" k=2时断开   
  14.     print( tt[i] )   
  15. end   
  16.   
  17. -- [[示例2.]] --   
  18. tbl = {"alpha""beta", [3] = "uno", ["two"] = "dos"}   
  19.   
  20. for i,v in ipairs(tbl) do    --输出前三个   
  21.     print( tbl[i] )   
  22. end   
  23.   
  24. for i,v in pairs(tbl) do    --全部输出   
  25.     print( tbl[i] )   
  26. end  

本文地址:http://www.92csz.com/00/1038.html
如非注明则为本站原创文章,欢迎转载。转载请注明转载自:moon's blog
 

目前有 3 条留言 其中:访客:3 条, 博主:0 条

  1. 朱定聪的博客 : 2012年01月31日01:56:23  -49楼

    😮 技术活呀~~

  2. 少年药王 : 2012年04月13日11:46:26  -48楼

    不断的在学习技术。

  3. 小熊依 : 2012年12月29日15:59:35  -47楼

    http://blog.csdn.net/bosbear/article/details/6317242#reply
    跟我以前写过的一篇日志基本上一样