[Conversion] Lua language basic summary (6) -- iterator and generic

Source: Internet
Author: User

Preface

An iterator is a mechanism that can traverse all elements in a collection. In Lua, The iterator is usually represented as a function. Each time the sequence function is called, the "Next" element in the set is returned. Each iterator needs to save some status after each successful call so that it can know its location and how to proceed to the next position. Through the summary in the previous blog, closures provide excellent support for such tasks. Now we use code to implement a simple iterator.

123456789101112 function values(tb)     local i = 0     return function ()          i = i + 1          return tb[i]     endend local testTb = {10, 20, 30}for value in values(testTb) do     print(value)end

This is the simplest iterator that uses closures to complete the entire task. This is just a simple example. Next, let's look at the semantics of generic.

 

Semantics of generic

Generic for is complex. It saves iterator functions during the loop process. It actually stores three values: An iterator function, a constant state, and a control variable. Next, we will summarize them separately.

 

The syntax of generic for is as follows:

123 for <var-list> in <exp-list> do     <body>end

 

<Var-List> is a list of one or more variable names separated by commas. <exp-List> is a list of one or more expressions, which are also separated by commas. Generally, the expression list has only one element, that is, a call to the iterator function. For example:

1 for k, v in pairs(t) do print(k, v) end

The first thing for is to evaluate the Expressions Behind in. These expressions should return three values for storage: iterator functions, constant states, and initial values of control variables. Here, it is the same as multi-value assignment. Only the last expression produces multiple results and only the first three values are retained. The excess values are discarded, it is supplemented with nil.

 

After Initialization is complete, for calls the iterator function with a constant state and control variable. Then, for assigns the return value of the iterator function to the variable in the Variable list. If the first return value is nil, the loop ends. Otherwise, for executes its loop body, then calls the iterator function again, and repeats the process. In the code in the preface, only the iterator function is returned, and the constant state and control variable are not returned. The following code illustrates this problem, for example:

1234567891011 for var_1, ..., var_n in <explist> do <Block> end -- is equivalent to the following code:do     Local _ F, _ s, _ Var = <explist> -- return the initial values of iterator functions, constant states, and control variables.     while true do          local var_1, ..., var_n = _f(_s, _var)          _var = var_1          if _var == nil then break end          <block>          end     endend

 

Stateless iterator

A stateless iterator is an iterator that does not store any state. Therefore, we can use the same stateless iterator in multiple loops to avoid the overhead of creating new closures.

 

In each iteration, the for loop uses a constant state and control variable to call the iterator function. A stateless iterator can generate the next element for the next iteration based on these two values. This type of iterator represents ipairs. It can be used to iterate all elements of an array. The Demo code is as follows:

1234 local aTb = {"One""Two""Three"}for i, v in ipairs(aTb) do     print(i, v)end

 

Here, the iterator state is the table to be traversed (a constant state, which will not change in the loop) and the current index value (control variable ). We can use the Lua code to implement ipairs, probably as follows:

1234567891011 local function iter(a, i)     i = i + 1     local v = a[i]     if v then          return i, v     endend function ipairs(a)     return iter, a, 0end

 

 

Like ipairs, the pairs function is used to traverse all elements in a table. The difference is that its iterator function is a basic function in Lua.

123 function pairs(a)     return next, t, nilend

 

 

When next (T, k) is called, K is a key of table t. This call will return a set of values in any order in the table: the next key of the table and the value corresponding to this key. When next (T, nil) is called, the first group of values in table is returned. If no value is set, next returns nil. Therefore, we can also use next to determine whether a table is empty.

 

The difference between ipairs and pairs, which are often confusing, can be clearly understood here. ipairs can only be used to traverse tables whose index is an integer type. At the same time, because the initial value of the control variable returned by ipairs is 0, this determines that ipairs can only access the key and value of index starting from 1; ipairs cannot return nil. When the value of the key is nil, The traversal is terminated directly; pairs has no requirements.

 

Of course, if there is a stateless iterator, there will be a stateful iterator. A stateful iterator uses a table to store the state; in the stateless iterator, every time we iterate a table, this table is a stateless table and it will not change during traversal, the stateful iterator changes the iterative table during the traversal process, and the status of the iterative table changes accordingly. I will not make a detailed summary here.

 

Http://cn.cocos2d-x.org/tutorial/show? Id = 1154

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.