Lua中ipairs()和pairs()的區別與使用
關於ipairs()和pairs(),Lua官方手冊是這樣說明的:
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會遍歷表中所有的key-value值,而ipairs會根據key的數值從1開始加1遞增遍歷對應的table[i]值,直到出現第一個不是按1遞增的數值時候退出。
下面我們以例子說明一下吧
stars = {[1] = "Sun", [2] = "Moon", [5] = 'Earth'}
for i, v in pairs(stars) do
print(i, v)
end
使用pairs()將會遍歷表中所有的資料,輸出結果是:
1 Sun
2 Moon
5 Earth
如果使用ipairs()的話,
for i, v in ipairs(stars) do
print(i, v)
end
當i的值遍歷到第三個元素時,i的值為5,此時i並不是上一個次i值(2)的+1遞增,所以遍歷結束,結果則會是:
1 Sun
2 Moon
ipairs()和pairs()的區別就是這麼簡單。
還有一個要注意的是pairs()的一個問題,用pairs()遍歷是[key]-[value]形式的表是隨機的,跟key的雜湊值有關係。看以下這個例子:
stars = {[1] = "Sun", [2] = "Moon", [3] = "Earth", [4] = "Mars", [5] = "Venus"}
for i, v in pairs(stars) do
print(i, v)
end
結果是:
2 Moon
3 Earth
1 Sun
4 Mars
5 Venus
並沒有按照其在表中的順序輸出。
但是如果是這樣定義表stars的話
stars = {"Sun", "Moon", “Earth”, "Mars", "Venus"}
結果則會是
1 Sun
2 Moon
3 Earth
4 Mars
5 Venus
你清楚了嗎?:)
相關文章
- Lua中pair和ipair的區別AI
- js中!和!!的區別與用法JS
- JavaCV與OpenCV的區別和使用中遇到的問題JavaOpenCV
- YII 的 with 與 joinwith 的區別和使用
- Android中 @和?區別以及?attr/**與@style/**等的區別Android
- su和sudo的區別與使用(轉)
- iOS中 Debug 和 Release 的區別和使用iOS
- C與C++中struct使用的區別C++Struct
- Node中Exports與module.export的使用與區別Export
- rem與em的使用和區別詳解REM
- javaSE中的==和equals的聯絡與區別Java
- Python引用型別和值型別的區別與使用Python型別
- Javascript中“==”與“===”的區別JavaScript
- js中“==”與"==="的區別JS
- FTP 中ascii 和bin 的區別和使用方法FTPASCII
- Python中eval與exec的使用及區別Python
- PHP中isset()與empty()的使用區別詳解PHP
- Oracle - @和@@、&與&& 的區別Oracle
- mysql中!=和is not的區別MySql
- JavaScript中for in 和for of的區別JavaScript
- mysql中“ ‘ “和 “ ` “的區別MySql
- Js中for in 和for of的區別JS
- vue watch 和 computed 區別與使用Vue
- PHP中empty、isset和is_null的使用區別PHPNull
- PHPCookie與Session的使用與區別PHPCookieSession
- PHP 中的 -> 和 :: 的區別PHP
- Java中(==)與equals的區別Java
- numpy中dot與*的區別
- Python中 ‘==‘ 與‘is‘的區別Python
- Mybatis中#{}和${}傳參的區別及#和$的區別小結MyBatis
- Python collections.defaultdict() 與 dict的使用和區別Python
- 使用jquery和使用框架的區別jQuery框架
- java 中equals和==的區別Java
- SQL中where和on的區別SQL
- Python 中 is 和 == 的區別Python
- Python中is和==的區別Python
- Java中equals和==的區別Java
- oracle中in和exists的區別Oracle