[LUA learning] differences between ipairs and pairs

Source: Internet
Author: User

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:nextFunction, 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 functionnextFor 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 ~~

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.