先看看官方手冊的說明吧:
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.
原來,pairs會遍歷table的所有鍵值對。如果你看過耗子叔的Lua簡明教程,你知道table就是鍵值對的數據結構。
而ipairs就是固定地從key值1開始,下次key累加1進行遍歷,如果key對應的value不存在,就停止遍歷。順便說下,記憶也很簡單,帶i的就是根據integer key值從1開始遍歷的。
請看個例子。
for k,v in ipairs(tb) do
print(k, v)
end
以上(為什么不少回答會以「以上」收尾?,這里就是結束的意思吧)
新聞熱點
疑難解答