随笔 - 132  文章 - 51  trackbacks - 0
<2011年12月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿(7)

随笔分类

随笔档案

文章分类

文章档案

cocos2d-x

OGRE

OPenGL

搜索

  •  

最新评论

阅读排行榜

评论排行榜

标准库提供了集中迭代器,包括迭代文件每行的(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

 


下面举个例子吧!

 

 eg:

local tabFiles = {

[3] = "test2",

[6] = "test3",

[4] = "test1"

}

 

for k, v in ipairs(tabFiles) do

print(k, v)

end

 

 

猜测它的输出结果是什么呢?

 

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

 

>lua -e "io.stdout:setvbuf 'no'" "Test.lua"

>Exit code: 0

 

那么,如果是

for k, v in pairs(tabFiles) do

print(k, v)

end

则会输出所有 :
>lua -e "io.stdout:setvbuf 'no'" "Test.lua" 
3 test2
6 test3
4 test1
>Exit code: 0
现在改变一下表内容,
local tabFiles = {
[1] = "test1",
[6] = "test2",
[4] = "test3"
}
for k, v in ipairs(tabFiles) do
print(k, v)
end
现在的输出结果显而易见就是key=1时的value值test1

 >lua -e "io.stdout:setvbuf 'no'" "Test.lua" 

1 test1

>Exit code: 0 

--[示例1.]--
local tt 
=
{
    [
1= "test3",
    [
4= "test4",
    [
5= "test5"
}


for i,v in pairs(tt) do        -- 输出 "test4" "test3" "test5"
    print( tt[i] )
end

for i,v in ipairs(tt) do    -- 输出 "test3" k=2时断开
    print( tt[i] )
end





-- [[示例2.]] --
tbl 
= {"alpha""beta", [3= "uno", ["two"= "dos"}

for i,v in ipairs(tbl) do    --输出前三个
    print( tbl[i] )
end

for i,v in pairs(tbl) do    --全部输出
    print( tbl[i] )
end




posted on 2011-12-16 08:43 风轻云淡 阅读(20787) 评论(3)  编辑 收藏 引用 所属分类: LUA

FeedBack:
# re: lua 中pairs 和 ipairs区别[未登录] 2014-03-28 16:31 kyle
英语不好就别误人子弟了

---------------------------Yours-----------
pairs可以遍历表中所有的key,并且除了迭代器本身以及遍历表本身还可以返回nil;
但是ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。它只能遍历到表中出现的第一个不是整数的key

--------------------------Mine------------
pairs遍历表中全部key,value
ipairs从下标为1开始遍历,然后下标累加1,如果某个下标元素不存在就终止遍历。这就导致如果下标不连续或者不是从1开始的表就会中断或者遍历不到元素。  回复  更多评论
  
# re: lua 中pairs 和 ipairs区别 2015-08-01 13:15 damnimgood
感谢分享 获益了  回复  更多评论
  
# re: lua 中pairs 和 ipairs区别 2015-09-04 22:32 Rming
@kyle

谢谢分享  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理