lua自定义迭代器

迭代器

http://www.tutorialspoint.com/lua/lua_iterators.htm

迭代器能够让你遍历某个集合或者容器中的每一个元素。 对于lua来说, 集合通常指代 table, 用于创建变化的数据结构, 类似数组。

Iterator is a construct that enables you to traverse through the elements of the so called collection or container. In Lua, these collections often refer to tables, which are used to create various data structures like array.

通用For迭代器

通常使用的for循环, 配合in使用, in后的参数 就是一个迭代器函数。

A generic for iterator provides the key value pairs of each element in the collection. A simple example is given below.

array = {"Lua", "Tutorial"}

for key,value in ipairs(array)
do
   print(key, value)
end

对于迭代器函数, 根据迭代器函数中状态的维护, 可以分为如下两种类型, 有状态迭代器, 和 无状态迭代器。

In Lua we use functions to represent iterators. Based on the state maintenance in these iterator functions, we have two main types −

  • Stateless Iterators
  • Stateful Iterators

无状态迭代器

迭代器函数中不维护任何状态。

By the name itself we can understand that this type of iterator function does not retain any state.

Let us now see an example of creating our own iterator using a simple function that prints the squares of n numbers.

如下例子, 迭代状态, 由for的参数 i 记录。

function square(iteratorMaxCount,currentNumber)

   if currentNumber<iteratorMaxCount
   then
      currentNumber = currentNumber+1
      return currentNumber, currentNumber*currentNumber
   end

end

for i,n in square,3,0
do
   print(i,n)
end

改进版:

function square(iteratorMaxCount,currentNumber)

   if currentNumber<iteratorMaxCount
   then
      currentNumber = currentNumber+1
      return currentNumber, currentNumber*currentNumber
   end

end

function squares(iteratorMaxCount)
   return square,iteratorMaxCount,0
end  

for i,n in squares(3)
do
   print(i,n)
end

有状态迭代器

利用闭包,将状态管理在闭包类, 迭代器函数为闭包。

The previous example of iteration using function does not retain the state. Each time the function is called, it returns the next element of the collection based on a second variable sent to the function. To hold the state of the current element, closures are used. Closure retain variables values across functions calls. To create a new closure, we create two functions including the closure itself and a factory, the function that creates the closure.

Let us now see an example of creating our own iterator in which we will be using closures.

如下例子,推荐使用如下写法,减少信息暴漏:

array = {"Lua", "Tutorial"}

function elementIterator (collection)

   local index = 0
   local count = #collection

   -- The closure function is returned

   return function ()
      index = index + 1

      if index <= count
      then
         -- return the current element of the iterator
         return collection[index]
      end

   end

end

for element in elementIterator(array)
do
   print(element)
end

自定义例子

使用有状态迭代器, 实现字符串拆分为固定长度的字符串:

local instr = "2334t545dfgjkkkk"

function StrSegIterator (str, segSize)
 local strIndex = 1

 -- The closure function is returned
 return function ()
  local segStart = strIndex
  local segEnd = strIndex + segSize - 1
  local strseg = string.sub(str, segStart, segEnd)

  if #strseg > 0 then
   strIndex = strIndex + segSize

   -- return the current element of the iterator
   return strseg
  end

 end

end

for element in StrSegIterator(instr, 2)
do
   print(element)
end
时间: 2024-08-11 05:46:12

lua自定义迭代器的相关文章

Lua iterator 迭代器

Lua有迭代器的概念,通过不同的迭代器,几乎可以遍历所有的东西.标准库提供的几种迭代器:io.lines(迭代文件中的每行), pairs(迭代table元素),ipairs(迭代数组元素), string.gmatch(迭代字符串中单词)等. 另外,可以自定义迭代器 使用pairs迭代器变量table > t = {2,3,4,5} > for i,v in pairs(t) do >> print(i .. ' = ' .. v) >> end 1 = 2 2 =

(转载)我所理解Cocos2d-x 3.6(Lua):Cocos如何绑定Lua自定义类

我所理解Cocos2d-x 3.6(Lua):Cocos如何绑定Lua自定义类 热血枫叶2015-06-19 16:27:182289 次阅读 Cocos2d-x 2.x 与 Cocos2d-x 3.x 差异(tolua++) Cocos2d-x在2.x版本里就是用toLua++和.pkg文件这么把自己注册进Lua环境里的,然而从Cocos2d-x 3.x开始,用bindings-generator脚本代替了toLua++. bindings-generator脚本的工作机制是: 1.不用编写.

Lua程序设计 迭代器与closure

所谓"迭代器"就是一种可以遍历一种集合中所有元素的机制.在Lua中,通常将迭代器表示为函数.每调用一次函数,即返回集合中的"下一个"元素. 每个迭代器都需要在每次成功调用之间保持一些状态,这样才能知道它所在的位置及如何步进到下一个位置.在Lua中,closure对于这类任务提供了极佳的支持,一个closure就是一种可以访问其外部嵌套环境中的局部变量的函数.对于closure而言,这些变量就可用于在成功调用之间保持状态值,从而使closure可以记住它在一次遍历中所

Apex 中的自定义迭代器

迭代器 迭代器(iterator)可以遍历一个集合变量中的每个元素.Apex提供了Iterator接口来让开发者实现自定义的迭代器. Iterator接口 Iterator接口定义了两个函数: hasNext():返回Boolean类型,表示被遍历的集合变量中是否还有下一个元素 next():返回集合变量中要被遍历的下一个元素 实现Iterator接口的类中所有的函数必须是global或public的. 示例代码(摘录自官方文档): global class CustomIterable imp

Python迭代和解析(4):自定义迭代器

本文介绍如何自定义迭代器,涉及到类的运算符重载,包括__getitem__的索引迭代,以及__iter__.__next__和__contains__,如果不了解这些知识可跳过本文. 索引迭代方式 索引取值和分片取值 元组.列表.字典.集合.字符串都支持索引取值操作和分片操作. >>> L = [11,21,31,41] >>> L[0] 11 >>> L[0:2] [11, 21] 分片操作实际上将一个slice对象当作索引位传递给序列,然后以索引取

我所理解cocos2d-x 3.6 lua -- Cocos如何绑定Lua自定义类

cocos2d-x 2.x 与 cocos2d-x 3.x 差异(tolua++) cocos2d-x在2.x版本里就是用toLua++和.pkg文件这么把自己注册进Lua环境里的,然而从cocos2d-x 3.x开始,用bindings-generator脚本代替了toLua++. bindings-generator脚本的工作机制是:        1.不用编写.pkg和.h文件了,直接定义一个ini文件,注册到Lua环境里的模块名是什么,就行了.        2.摸清了toLua++工具

自定义迭代器:比如输入奇数项,反向迭代等

有时需要自定义一个迭代模式,如以0.5的步长迭代,或者只输出奇数项,反向迭代等 所谓的迭代器其实也是使用了next方法,所以,只要 合理利用next,就可以达到目的: #!/usr/bin/env python #coding:utf-8 #@Author:Andy #Date: 2017/6/13 def frange(start, stop, step): """ Use yield to set a new iteration pattern such as float

python自定义迭代器对象以及可迭代对象

# coding=utf8 from collections import Iterator from collections import Iterable #迭代器对象 class OwnIteror( Iterator ): def __init__(self , arrs ): self.index = 0 self.arrs = arrs def next(self): if self.index > len( self.arrs ) - 1: raise StopIteration

Java 经典实例:自定义迭代器

编写自己的Iterator,实现Iterator接口,这里多说一句,实现Iterable后,可以用"foreach"循环遍历你的对象. import java.util.Iterator; import java.util.NoSuchElementException; /** * 演示Iterator和Iterable接口,并说明怎样编写一个用于对象数组的简单迭代器. */ public class AarrayIterator<T> implements Iterabl