功能强大的 For 第二型

for 语句的第二种用法很难懂,跟我们以前的理念都不一样。

其形式如下:

for var {, var} in explist do block end

在循环开始之前,explist 会被计算出值,只计算一次
explist is evaluated once before the loop is entered. Its results are an iterator function (which sets the var values), a state (from which the values can be read), and an initial value (from which to iterate onwards).

pairs(table)

Lua 提供了 pairs() 函数来遍历性地产生传递给它的表的 key-value 对信息。
Lua provides a pairs() function to create the explist information for us to iterate over a table. The pairs() function will allow iteration over key-value pairs. Note that the order that items are returned is not defined, not even for indexed tables.

> for key,value in pairs(t) do print(key,value) end
3 10
1 3
4 17
2 7
pi 3.14159
banana yellow

ipairs(table)

Lua 提供了 ipairs() 函数来遍历性地产生传递给它的表的 index-value 对信息。
The ipairs() function will allow iteration over index-value pairs. These are key-value pairs where the keys are indices into an array. The order in which elements are returned is guaranteed to be in the numeric order of the indices, and non-integer keys are simply skipped. Using the same table as in the example above:

> for index,value in ipairs(t) do print(index,value) end
1 3
2 7
3 10
4 17

Notice how only the array part of the table is displayed because only these elements have index keys.

next()

The next(table [,index]) function helps iterate over a table. When given a table and an index it returns the next key-value pair from the table, e.g.,

> = next(t) — index will be nil, the beginning
1 3
> = next(t,"pi")
banana yellow

As with pairs(), the order in which items are returned is not defined; index keys can be returned in any order, not just numerically increasing. The pairs() function returns an explist containing next() so we can iterate over tables. We can pass our own expression list to the for statement as follows:

> for key,value in next,t,nil do print(key,value) end
1 3
2 7
3 10
4 17
pi 3.14159
banana yellow

We pass next,table,nil as the expression list to the for statement. We are saying here that we want to use the iterator function next(), on the table called "table", starting at nil (the beginning). The for statement keeps executing until the next() function returns nil (the end of the table).

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License