Lua ipairs、pairs
??先給出 lua 官方 reference 中 ipairs 和 pairs 的解釋:
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.
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 有兩個返回值,分別是 function 和 table,ipairs 返回三個,前兩個和 pairs 一樣,最后多返回一個 0.
??我們可以直接在代碼里這樣使用:
??Lua 中表格的存儲可以看 ++待填入鏈接++,本篇博客關(guān)注 ipairs 和 pairs 的區(qū)別。
??可以看到,和上邊鏈接中講到的一樣,ipairs 從下標(biāo)為 1 開始輸出,直到當(dāng)前下標(biāo)對應(yīng)值為 nil 為止,pairs 則都輸出了。
??通過 func,t,idx 獲取到 ipairs 的返回值后,可以通過 for i, v in func, t, idx do 這種方式達(dá)到同樣的遍歷效果,下邊三種方式是一樣的:
for i, v in func, t, idx do
for i, v in func, tab, 0 do
for i, v in ipairs(tab) do
??通過修改第二個參數(shù)為新的 table,可以達(dá)到遍歷新的 table 的目的,通過修改第三個參數(shù) idx,可以達(dá)到對初始位置進(jìn)行偏移的效果,從 -1 開始則什么都不會輸出,從 0 開始就和默認(rèn)的是一模一樣的,從 1 開始就會向后偏移一個位置開始輸出。
??pairs 同理但是沒有第三個返回值。
總結(jié)
以上是生活随笔為你收集整理的Lua ipairs、pairs的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mongodb数据备份
- 下一篇: 人工智能两大技术驱动力