pairs (t)If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.
Otherwise, 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 (t)If t has a metamethod __ipairs, calls it with t as argument and returns the first three results from the call.
Otherwise, 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.
原來(lái),pairs會(huì)遍歷table的所有鍵值對(duì)。如果你看過(guò)耗子叔的Lua簡(jiǎn)明教程,你知道table就是鍵值對(duì)的數(shù)據(jù)結(jié)構(gòu)。
而ipairs就是固定地從key值1開始,下次key累加1進(jìn)行遍歷,如果key對(duì)應(yīng)的value不存在,就停止遍歷。順便說(shuō)下,記憶也很簡(jiǎn)單,帶i的就是根據(jù)integer key值從1開始遍歷的。
tb = {"oh", [3] = "god", "my", [5] = "hello", [6] = "world"}
for k,v in ipairs(tb) do
print(k, v)
end