The difference between Ipair and pair in Lua _lua

Source: Internet
Author: User

Let's take a look at the official manual:

Copy Code code as follows:


Otherwise, returns three values:the next function, the table T, and Nil, so this construction
For k,v in pairs (t) does body end
Would iterate over the all key–value pairs of table T.
The caveats of modifying the table during its traversal.


Otherwise, returns three Values:an iterator function, the table T, and 0, so this construction
For i,v in Ipairs (t) does body end
Would iterate over the pairs (1,t[1]), (2,t[2), ..., up to the "the" "the", "the", "the".

Originally, pairs would traverse all key-value pairs of the table. If you have read the Lua concise tutorial of mouse uncle, you know that table is the data structure of the key value pair.

And Ipairs is fixed to start from the key value 1, the next key accumulation of 1 to traverse, if the key corresponding value does not exist, stop traversal. By the way, memory is also very simple, with I is based on the integer key value from 1 to begin traversing.

Take a look at an example.

Copy Code code as follows:

TB = {"Oh", [3] = "God", "I", [5] = "Hello", [6] = "World"}

For k,v in Ipairs (TB) do
Print (k, v)
End


The output results are:
Copy Code code as follows:

1 OH
2 my
3 God

Because TB does not exist tb[4], the traversal ends here.
Copy Code code as follows:

For k,v in pairs (TB) do
Print (k, v)
End

Output results:
Copy Code code as follows:

1 OH
2 my
3 God
6 World
5 Hello

We can all guess that will output all the content. You find, however, that the order of output differs from the order in which you have TB.
What if we want to output sequentially? One approach is:
Copy Code code as follows:

For i = 1, #tb do
If Tb[i] Then
Print (Tb[i])
Else
End

Of course, just the number of groups, Ipairs is no problem.

Above (why do many answers end with "above"?) , here's what it means to end it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.