佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > Lua中ipair和pair的區(qū)別

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

熱門(mén)標(biāo)簽:呼叫中心市場(chǎng)需求 Linux服務(wù)器 鐵路電話系統(tǒng) 服務(wù)外包 地方門(mén)戶網(wǎng)站 AI電銷 網(wǎng)站排名優(yōu)化 百度競(jìng)價(jià)排名

先看看官方手冊(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開(kāi)始,下次key累加1進(jìn)行遍歷,如果key對(duì)應(yīng)的value不存在,就停止遍歷。順便說(shuō)下,記憶也很簡(jiǎn)單,帶i的就是根據(jù)integer key值從1開(kāi)始遍歷的。

請(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é)束的意思吧)

標(biāo)簽:銅川 蘭州 衡水 仙桃 崇左 黃山 湘潭 湖南

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Lua中ipair和pair的區(qū)別》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    英德市| 米泉市| 丰县| 通化市| 黎城县| 平潭县| 延寿县| 永胜县| 桂东县| 安阳县| 新平| 南丰县| 绥化市| 新乡市| 金沙县| 姜堰市| 新田县| 子洲县| 张家口市| 颍上县| 洛宁县| 乾安县| 义马市| 宝丰县| 周口市| 沭阳县| 华池县| 巫溪县| 荣成市| 嘉祥县| 安吉县| 左权县| 丰台区| 鲁甸县| 大名县| 平舆县| 玉龙| 柳河县| 滕州市| 焦作市| 招远市|