麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > 綜合 > 正文

Lua中ipair和pair的區別

2024-07-21 23:04:05
字體:
來源:轉載
供稿:網友

先看看官方手冊的說明吧:

 

復制代碼 代碼如下:

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.

 

原來,pairs會遍歷table的所有鍵值對。如果你看過耗子叔的Lua簡明教程,你知道table就是鍵值對的數據結構。

而ipairs就是固定地從key值1開始,下次key累加1進行遍歷,如果key對應的value不存在,就停止遍歷。順便說下,記憶也很簡單,帶i的就是根據integer key值從1開始遍歷的。

請看個例子。

 

復制代碼 代碼如下:

tb = {"oh", [3] = "god", "my", [5] = "hello", [6] = "world"}

 

for k,v in ipairs(tb) do
     print(k, v)
end


輸出結果就是:
復制代碼 代碼如下:

1       oh
2       my
3       god

因為tb不存在tb[4],所以遍歷到此為止了。
復制代碼 代碼如下:

for k,v in pairs(tb) do
     print(k, v)
end

輸出結果:
復制代碼 代碼如下:

1       oh
2       my
3       god
6       world
5       hello

我們都能猜到,將輸出所有的內容。然而你發現輸出的順序跟你tb中的順序不同。
如果我們要按順序輸出怎么辦?辦法之一是:
復制代碼 代碼如下:

for i = 1, #tb do
     if tb[i] then
          print(tb[i])
     else
end

當然,僅僅是個數組的話,ipairs也沒問題。

 

以上(為什么不少回答會以「以上」收尾?,這里就是結束的意思吧)

 
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: www.777含羞草| 黄色一级电影网 | 看国产毛片 | 色视频在线播放 | 午夜精品视频在线 | 欧美日韩大片在线观看 | 久久嗨| 国产精品美女久久久久久不卡 | 久久欧美亚洲另类专区91大神 | 双性帝王调教跪撅打屁股 | 成年人高清视频在线观看 | 香蕉久草视频 | 91亚洲免费视频 | 国产精品av久久久久久久久久 | 中国a毛片| 久久91精品国产91久久yfo | 美女黄视频在线观看 | 亚洲av一级毛片特黄大片 | 国产精品成人久久久久a级 av电影在线免费 | 亚洲va久久久噜噜噜久牛牛影视 | 在线观看91精品 | 九九精品在线观看视频 | 全免费午夜一级毛片真人 | 成人午夜精品久久久久久久蜜臀 | 国产亚洲美女精品久久久2020 | 国产小视频在线观看 | 欧美一级电影网站 | 国产激情精品一区二区三区 | 久久久久久久亚洲精品 | 青青草成人免费视频在线 | 国产九色在线观看 | 成人性视频在线 | 日本精品久久久久 | 国产成人综合在线观看 | 免费观看视频91 | 欧美成人免费小视频 | 美女亚洲 | 亚洲一区二区中文字幕在线观看 | 国产一区二区精品91 | 久章草影院| 久久蜜桃精品一区二区三区综合网 |