• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Lua table pair和ipair区别

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

官方描述:

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。

更多:http://blog.csdn.net/tony7758/article/details/6334001

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
还原Lua调用栈发布时间:2022-07-22
下一篇:
lua的string库函数总结发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap