Lua Tutorial (v): iterators and generics For_lua

Source: Internet
Author: User

1. Iterators and Closure:

In Lua, an iterator is typically a function that returns the "next" element in the collection every time a function is invoked. Each iterator needs to maintain some state between each successful invocation in order to know where it is and where it will be at the next traversal. From this point of view, the closure mechanism in LUA provides linguistic support for this issue, as shown in the following example:

Copy Code code as follows:

function values (t)
Local i = 0
return function ()
i = i + 1
return T[i]
End
End
t = {10, 20, 30}
it = VALUES (t)
While True
Local element = it ()
if element = = Nil Then
Break
End
Print (Element)
End
--another way of calling based on foreach (generics for)
T2 = {15, 25, 35}
for element in values (t2) do
Print (Element)
End
--The output result is:
--10
20th
--30
--15
--25
--35

From the example above, the generic for method provides clearer implementation logic than the while approach. Because Lua saves us an iterator function internally, it calls the implicit internal iterator every iteration, until the iterator returns to nil and ends the loop.

2. Generic for semantics:

The iterator in the example above has an obvious drawback that a new closure variable needs to be created each time the loop is successful, or the first iteration succeeds, and then the closure is exited directly when it is used in the new for loop.

Here we'll explain in detail the generic (for) mechanism in Lua, and then give an example of a stateless iterator for our understanding. If our iterator is implemented as a stateless iterator, then it is not necessary to declare a new iterator variable for each generic (for).
The syntax for generics (for) is as follows:

Copy Code code as follows:

For <var-list> in <exp-list> do
<body>
End

For the sake of understanding, because we are in the actual application of <exp-list> usually only contains an expression (expr), so for simplicity, the description here will just include an expression, not an expression list. Now let's start with the prototype and instance of the expression, such as:
Copy Code code as follows:

function Ipairs2 (a)
Return iter,a,0
End

The function returns 3 values, the first is the actual iterator function variable, and the second is a constant object, which we can understand as the container to be traversed, and the third variable is the initial value to be passed in when the ITER () function is invoked.
Now let's look at the implementation of the ITER () function, such as:
Copy Code code as follows:

Local function iter (a, i)
i = i + 1
Local v = a[i]
If V Then
return I, V
Else
return nil, Nil
End
End

In the iterator function iter (), two values are returned, corresponding to the key and value of the table, where key (the returned i) is nil, and the generic (for) will assume that this iteration has ended. Now let's take a look at the actual use cases, such as:

Copy Code code as follows:

function Ipairs2 (a)
Return iter,a,0
End


Local function iter (a, i)
i = i + 1
Local v = a[i]
If V Then
return I, V
Else
return nil, Nil
End
End

A = {"One", "two", "three"}
For k,v in Ipairs2 (a) do
Print (k, v)
End
--The output result is:
--1 One
--2 Two
--3 Three

The generic (for) notation in this example can be expanded to the following method based on a while loop, such as:

Copy Code code as follows:

Local function iter (a, i)
i = i + 1
Local v = a[i]
If V Then
return I, V
Else
return nil, Nil
End
End

function Ipairs2 (a)
Return iter,a,0
End

A = {"One", "two", "three"}
Todo
Local _it,_s,_var = Ipairs2 (a)
While True
Local var_1,var_2 = _it (_s,_var)
_var = var_1
if _var = = Nil Then-note that only the first one returned by the iterator function is judged to be nil.
Break
End
Print (var_1,var_2)
End
End
--the output is ditto.


3. Examples of stateless iterators:
The example here will implement an iterator that traverses the list.
Copy Code code as follows:

Local function GetNext (list, node)--iterator function.
If not node then
Return list
Else
Return Node.next
End
End

function traverse (list)--expression of generics (for)
Return Getnext,list,nil
End

--initializes the data in the linked list.
List = Nil
For line in Io.lines () do
Line = {val = line, next = list}
End

--traverse the list in the form of a generic (for).
For node in traverse (list) do
Print (Node.val)
End

The trick here is to use the first node of the linked list as a constant state (the second value returned by Traverse), and the current nodes as control variables. The first time the iterator function GetNext () is invoked, node is nil, so the function returns the list as the first node. node is no longer nil in subsequent calls, so the iterator returns node.next until it returns the nil node at the end of the list, at which point the generic (for) determines that the iterator's traversal has ended.

The last thing to note is that the Traverse () function and list variable can be called repeatedly without creating a new closure variable. This is mainly because the iterator function (GetNext) is implemented as a stateless iterator.

4. Iterators with complex states:

In the iterator implementation described above, iterators need to save many states, but generics (for) provide only constant state and control variables for state preservation. One of the easiest ways to do this is to use closure. Of course, we also encapsulate all the information into a table and pass it to the iterator as a constant state object. Although the constant state variable itself is constant, that is, it is not exchanged for other objects during the iteration, the data contained in the object varies depending entirely on the implementation of the iterator. For now, because the constant object of the table type already contains all the information that the iterator relies on, the iterator can completely ignore the second parameter provided by the generic (for). So let's give you an example of the following code:

Copy Code code as follows:

Local iterator
function Allwords ()
Local state {line = Io.read (), pos = 1}
Return iterator, State
End
The--iterator function will be the real iterator
function iterator (state)
While State.line do
Local s,e = String.find (State.line, "%w+", State.pos)
If S Then
State.pos = e + 1
Return String.sub (state.line,s,e)
Else
State.line = Io.read ()
State.pos = 1
End
End
return Nil
End

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.