lua中pairs和ipairs的比较

来源:互联网 发布:天谕捏脸数据男魔王 编辑:程序博客网 时间:2024/06/08 15:14

        最近几天跟着老大的节奏搞了几天Lua,刚开始有点不适应Lua脚本这种编写习惯,不过慢慢的就适应了。

原文地址:http://www.cppblog.com/wc250en007/archive/2011/12/16/162203.html

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

下面是例子

local tabFiles = {[3] = "test2",[6] = "test3",[4] = "test1"}for k, v in ipairs(tabFiles) doprint(k, v)end
猜测它的输出结构是什么呢?

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

那么如果是

for k, v in pairs(tabFiles) doprint(k, v)end
则会输出所有:

3 test2

6 test3

4 test1

现在改变一下表格的内容

local tabFiles = {[1] = "test1",[6] = "test2",[4] = "test3"}for k, v in ipairs(tabFiles) doprint(k, v)end
现在的输出结构显而易见就是key = 1时的value test1

1 test1

再看两个例子

local tab = {[1] = "test3", [4] = "test4", [5] = "test5"}for i, v pairs(tab) doprint(tab[i])--输出"test3" "test4" "test5"endfor i, v ipairs(tab) doprint(tab[i])--输出"test3" k = 2时断开end

tab = {"alpha", "beta", [3] = "uno", ["two"] = "dos"}for i, v ipairs(tab) doprint(tab[i])--输出"alpha" "beta" "uno"endfor i, v pairs(tab) doprint(tab[i])--输出"alpha" "beta" "uno" "dos"end

0 0