国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開發(fā) > 綜合 > 正文

Lua中ipair和pair的區(qū)別

2024-07-21 23:04:05
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

先看看官方手冊(cè)的說(shuō)明吧:

 

復(fù)制代碼 代碼如下:

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開始遍歷的。

請(qǐng)看個(gè)例子。

 

復(fù)制代碼 代碼如下:

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

 

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


輸出結(jié)果就是:
復(fù)制代碼 代碼如下:

1       oh
2       my
3       god

因?yàn)閠b不存在tb[4],所以遍歷到此為止了。
復(fù)制代碼 代碼如下:

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

輸出結(jié)果:
復(fù)制代碼 代碼如下:

1       oh
2       my
3       god
6       world
5       hello

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

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

當(dāng)然,僅僅是個(gè)數(shù)組的話,ipairs也沒(méi)問(wèn)題。

 

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

 
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 土默特右旗| 新余市| 榆树市| 榆林市| 醴陵市| 富顺县| 曲周县| 长春市| 武穴市| 长海县| 游戏| 大竹县| 东港市| 彭州市| 金乡县| 文山县| 曲麻莱县| 甘洛县| 仁布县| 五常市| 昌乐县| 高安市| 会理县| 钦州市| 红原县| 贺州市| 云阳县| 西昌市| 绍兴县| 通河县| 汕尾市| 郴州市| 讷河市| 金堂县| 元朗区| 苏尼特左旗| 嫩江县| 修文县| 金昌市| 修文县| 常熟市|