Looking at LUA over the past few days, I just recorded my little experiences. This article analyzes the differences between ipairs and pairs provided by LUA generic.
The standard library provides a centralized iterator, including io. lines in each row of the iteration file, pairs, ipairs, and
(String. gmatch) and so on. The LUA manual explains pairs and ipairs as follows:
ipairs (t)
Returns three values: an iterator function, the tablet
, 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 (t)
Returns three values:next
Function, the tablet
, AndNil, So that the construction
for k,v in pairs(t) do body end
Will iterate over all key-value pairs of tablet
.
See functionnext
For the caveats of modifying the table during its traversal.
In this way, we can see the differences between ipairs and pairs.
Pairs can traverse all keys in the table, and can return nil in addition to the iterator itself and the traversal table itself;
However, ipairs cannot return nil, but only returns 0. If nil is encountered, it exits. It can only traverse the first key that is not an integer in the table.
The following is an example!
Eg:
Guess what the output result is?
According to the analysis just now, it is in ipairs (tabFiles) traversal. When key = 1, the value is nil, so directly jumping out of the loop does not output any value.
If yes
The output will be all: Change the table content, and the output result is obviously the value test1 of key = 1.
Now, I have already made it clear. continue later ~~