這幾天在看LUA,只是記錄下自己的一點小小心得。這篇是分析 LUA泛型for中提供的ipairs以及pairs的不同。
標準庫提供了集中迭代器,包括迭代文件每行的(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:
猜測它的輸出結果是什麼呢?
根據剛纔的分析,它在 ipairs(tabFiles) 遍歷中,當key=1時候value就是nil,所以直接跳出循環不輸出任何值。
那麼,如果是
好了現在已經說的很清楚啦,以後繼續咯~~