标签:
先看一段简单的代码:
local mytable = { 1, 2, aa = "abc", subtable = {}, 4, 6 } --for循环1 print("for --- index") for i=1,#mytable do print(i) end --for循环2 print("for ---- index-value") for i,v in ipairs(mytable) do print(i,v) end --for循环3 print("for ---- key-value") for k,v in pairs(mytable) do print(k,v) end
输出结果:
for --- index 1 2 3 4 for ---- index-value 1 1 2 2 3 4 4 6 for ---- key-value 1 1 2 2 3 4 4 6 subtable table: 0x7f82d8d07660 aa abc
3种for循环的结果各不相同,我们这里对后两种进行一下比较。
看一下,关于pairs和ipairs的定义:
pairs (t)If
thas a metamethod__pairs, calls it withtas argument and returns the first three results from the call.Otherwise, returns three values: the
nextfunction, the tablet, and nil, so that the constructionfor k,v in pairs(t) do body endwill iterate over all key–value pairs of table
t.See function
nextfor the caveats of modifying the table during its traversal.
ipairs (t)
Returns three values (an iterator function, the table
t, and 0) so that the constructionfor i,v in ipairs(t) do body endwill iterate over the key–value pairs (
1,t[1]), (2,t[2]), ..., up to the first nil value.
例如:
local mytable2 = { [2] = "b", [3] = "c" } for i,v in ipairs(mytable2) do print(i,v) end
这里什么都不会输出,当迭代key=1的键值对时,value=nil,直接跳出;
所以:
所以要根据不同的需求,使用不同的方法。
标签:
原文地址:http://www.cnblogs.com/zzya/p/5778125.html