Let's take a look at the instructions in the official manual:
pairs (t)If t has a metamethod __pairs, calls it 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, calls it 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.
It turns out that pairs will iterate through all key-value pairs of tables. If you've seen Uncle MouseLua's simple tutorial, you know that table is the data structure of key-value pairs.
The ipairs is to start from the key value 1 fixedly, and then add 1 to traverse the key next time. If the value corresponding to the key does not exist, stop traversing. By the way, memory is also very simple. The one with i is traversed from 1 according to the integer key value.
Please 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 tb[4], the traversal ends here.
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 everything will be output. However, you find that the order of output is different from the order in your tb.
What if we want to output in order? One of the solutions is:
for i = 1, #tb do
if tb[i] then
print(tb[i])
else
end
Of course, if it's just an array, there's no problem with ipairs.
The above (Why do many answers end with "the above"?, here is the ending meaning)