
下一站.jpg
前言
以前我們要遍歷一個table的是否往往會是用for循環(huán),如果不是數(shù)字索引的表只能使用pairs了,今天這個函數(shù)提供了一個方法,就是不斷的查詢下一個元素的索引和對應(yīng)的值,來達(dá)到遍歷table的目的,接下來我們一起來看一下實現(xiàn)的方法。
內(nèi)容
next()
next(table [, index])
解釋:使程序可以遍歷表table的所有字段。他的第一個參數(shù)是一個表,第二個參數(shù)是一個表中有效的索引。函數(shù)會返回表中相對于指定索引的下一個索引和索引位置的值,當(dāng)我們將第二個參數(shù)設(shè)置為
nil調(diào)用函數(shù)時,函數(shù)會返回這個表的初始索引和該索引位置的值,當(dāng)我們使用表的最后一個索引或者在空表中使用nil做索引時,函數(shù)就會返回nil。當(dāng)我們省略第二個參數(shù)時,它會被默認(rèn)解釋成nil。特別的,你可以使用next(t)的形式來檢測表是否為空。使用這個函數(shù)獲得的索引是未指定順序的枚舉,即使是對于數(shù)字類型的索引也是一樣(如果要以數(shù)字的順序遍歷一個表,應(yīng)該是使用數(shù)字類型的
for或者是ipairs函數(shù))。函數(shù)如果在遍歷期間你給一個并不存在的字段賦值,其行為的結(jié)果是未定義的。不過你可以修改已經(jīng)存在的字段,也可以清除已經(jīng)存在的字段。
Usage
- 首先我們新建一個文件將文件命名為nexttest.lua然后編寫代碼如下:
-- 定義一個測試表
local tab = {
x = 1,
y = 66,
[100] = 100,
[3] = 3,
}
-- 判斷表是否為空
local index, value = nil, nil
index, value = next(tab)
if index ~= nil then
print("\ntable tab is not nil")
end
-- 遍歷table
print("\ntraverse table result:")
while index ~= nil do
print("[\""..index.."\"] = "..value);
index, value = next(tab, index)
end
index = "x"
index, value = next(tab, index)
-- 再次遍歷table
print("\ntraverse table again result:")
while index ~= nil do
print("[\""..index.."\"] = "..value);
index, value = next(tab, index)
end
-- 傳入最后索引
local ret = next(tab, 100)
print("\nlast index test ret is", ret)
-- 傳入空表
local ret = next({}, nil)
print("\nnil table test ret is", ret)
-- 傳入不存在索引
local ret = next(tab, 1000)
print("\nerror index test ret is", ret)
- 運行結(jié)果

base_next.png
總結(jié)
- 函數(shù)的解釋中所要注意的問題我在例子中都做了測試,大家看一下測試結(jié)果接就好。
- 其中最需要注意的就是在函數(shù)的遍歷期間向表中添加數(shù)據(jù)的情況,這種結(jié)果未定義,我們要盡量避免。
- 當(dāng)傳入無效索引時函數(shù)會報錯,所以還不是不要隨便傳入一個索引,而應(yīng)該使用這個函數(shù)返回的索引