The basic Lua Library provides ipairs, an iterator function that traverses arrays.
In each loop, I is assigned an index value, and V is assigned an array element value that should be indexed by the team.
The standard library provides several iterators, including
Each line (Io. lines ),
Iterative table elements (pairs ),
Iteration array elements (ipairs ),
The word in the iteration string (string. gmatch)
You can also compile your own iterator.
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:
local tabFiles = { [3] = "test2", [6] = "test3", [4] = "test1"} for k, v in ipairs(tabFiles) do print(k, v)end
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.
> LUA-e "Io. stdout: setvbuf 'No'" "test. Lua"
> Exit code: 0
If yes
for k, v in pairs(tabFiles) do print(k, v)end
The output will be all:> LUA-e "Io. stdout: setvbuf 'No'" "test. Lua" 3 test26 test34 test1> exit code: 0. Now, change the table content,
local tabFiles = { [1] = "test1", [6] = "test2", [4] = "test3"}for k, v in ipairs(tabFiles) do print(k, v)end
The output result is obviously the value test1 when key = 1.
> LUA-e "Io. stdout: setvbuf 'No'" "test. Lua"
1 test1
> Exit code: 0