一般用 “for 變量列表 in 迭帶器" 句型遍歷,即在in後面是迭帶器表達式,包含3個對象:迭帶函數、狀態常量、控制變量,當然狀態常量和控制變量可以不要。
迭帶過程:
1. 將狀態常量、控制變量傳給迭帶函數進行函數調用,將迭帶函數返回值賦給for變量列表,同時將返回的第一個值賦給控制變量。
2. 如果函數返回的第一個值爲nil則循環結束,否則執行循環體。
3. 循環體執行完後重復步驟1.
再看數組迭帶器ipairs:
ipairs (t)
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.
返回了三個東西:迭帶函數、數組本身、控制變量下標,顯然要求迭帶函數每次調用後能返回+1後的下標才能正常遍歷數組。
當然另一個迭帶器pairs函數返回的是next迭帶函數,靠next函數去遍歷。