What is the difference between lua's ipair and pair?
Let's take a look at the instructions in the official manual: pairs (t) If t has a metamethod _ pairs, callit with t as argument and returns the first three results from the call.
Otherwise, returns three values: the next function, the table t, and nil, so that the construction
For k, v in pairs (t) do body end
Will iterate over all key-value pairs of table t.
See function next for the caveats of modifying the table during its traversal.
Ipairs (t) If t has a metamethod _ ipairs, callit with t as argument and returns the first three results from the call.
Otherwise, 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.
Previously, pairs traversed all key-value pairs in the table. If you have read the simple Lua tutorial of Shuo, you know that table is the data structure of the key-value pair.
While ipairs is fixed starting from key value 1. The next time the key accumulates 1 for traversal, if the value corresponding to the key does not exist, the traversal will be stopped. By the way, the memory is also very simple. The memory with I is traversed from 1 Based on the integer key value.
See an example.
Tb = {"oh", [3] = "god", "my", [5] = "hello", [6] = "world "}
For k, v in ipairs (tb) do
Print (k, v)
End
The output result is:
1 oh
2 my
3 god
Because tb does not exist in tb [4], the traversal ends.
For k, v in pairs (tb) do
Print (k, v)
End
Output result:
1 oh
2 my
3 god
6 world
5 hello
We can all guess that all content will be output. However, you find that the output order is different from that in tb.
What if we want to output data in order? One of the methods is:
For I = 1, # tb do
If tb [I] then
Print (tb [I])
Else
End
Of course, ipairs is okay if it is just an array.
Above (Why do many answers end with "above ?, Here is the end)