As the name implies, a stateless iterator is an iterator that does not keep any state by itself. Therefore, we may use the same stateless iterator in multiple loops, avoiding the cost of creating new closures.

On each iteration, the for loop calls its iterator function with two arguments: the invariant state and the control variable. A stateless iterator generates the next element for the iteration using only these two arguments. A typical example of this kind of iterator is ipairs, which iterates over all elements in an array, as illustrated next:

    a = {"one", "two", "three"}
for i, v in ipairs(a) do
print(i, v)
end

The state of the iteration is the table being traversed (the invariant state, which does not change during the loop), plus the current index (the control variable). Both ipairs and the iterator it returns are quite simple; we could write them in Lua as follows:

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

When Lua calls ipairs(a) in a for loop, it gets three values: the iter function as the iterator, a as the invariant state, and zero as the initial value for the control variable. Then, Lua calls iter(a, 0), which results in 1, a[1] (unless a[1] is already nil). In the second iteration, it calls iter(a, 1), which results in 2, a[2], and so on, until the first nil element.

The pairs function, which iterates over all elements in a table, is similar, except that the iterator function is the next function, which is a primitive function in Lua:

    function pairs (t)
return next, t, nil
end

The call next(t, k), where k is a key of the table t, returns a next key in the table, in an arbitrary order. (It returns also the value associated with that key, as a second return value.) The call next(t, nil) returns a first pair. When there are no more pairs, next returns nil.

Some people prefer to use next directly, without calling pairs:

    for k, v in next, t do
...
end

Remember that the expression list of the for loop is adjusted to three results, so Lua gets nextt, and nil, exactly what it gets when it calls pairs(t).

标准库提供了集中迭代器,包括迭代文件每行的(io.lines),迭代table元素的(pairs),迭代数组元素的(ipairs),迭代字符串中单词的

(string.gmatch)等等。LUA手册中对与pairs,ipairs解释如下:

ipairs (t)

Returns three values: an iterator function, the table t, 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: the next function, the table t, and nil, so that the construction

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

这样就可以看出  ipairs以及pairs 的不同。

pairs可以遍历表中所有的key,并且除了迭代器本身以及遍历表本身还可以返回nil;

但是ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。它只能遍历到表中出现的第一个不是整数的key

 下面举个例子吧!

  eg:
local tabFiles = {
[] = "test2",
[] = "test3",
[] = "test1"
} for k, v in ipairs(tabFiles) do
print(k, v)
end 猜测它的输出结果是什么呢? 根据刚才的分析,它在 ipairs(tabFiles) 遍历中,当key=1时候value就是nil,所以直接跳出循环不输出任何值。 >lua -e "io.stdout:setvbuf 'no'" "Test.lua"
>Exit code: 那么,如果是
for k, v in pairs(tabFiles) do
print(k, v)
end
则会输出所有 :
>lua -e "io.stdout:setvbuf 'no'" "Test.lua"
test2
test3
test1
>Exit code:
现在改变一下表内容,
local tabFiles = {
[] = "test1",
[] = "test2",
[] = "test3"
}
for k, v in ipairs(tabFiles) do
print(k, v)
end
现在的输出结果显而易见就是key=1时的value值test1
>lua -e "io.stdout:setvbuf 'no'" "Test.lua"
test1
>Exit code:
--[示例1.]--
local tt =
{
[] = "test3",
[] = "test4",
[] = "test5"
} for i,v in pairs(tt) do -- 输出 "test4" "test3" "test5"
print( tt[i] )
end for i,v in ipairs(tt) do -- 输出 "test3" k=2时断开
print( tt[i] )
end -- [[示例2.]] --
tbl = {"alpha", "beta", [] = "uno", ["two"] = "dos"} for i,v in ipairs(tbl) do --输出前三个
print( tbl[i] )
end for i,v in pairs(tbl) do --全部输出
print( tbl[i] )
end

Stateless Iterators的更多相关文章

  1. lua自定义迭代器

    迭代器 http://www.tutorialspoint.com/lua/lua_iterators.htm 迭代器能够让你遍历某个集合或者容器中的每一个元素. 对于lua来说, 集合通常指代 ta ...

  2. Python标准模块--Iterators和Generators

    1 模块简介 当你开始使用Python编程时,你或许已经使用了iterators(迭代器)和generators(生成器),你当时可能并没有意识到.在本篇博文中,我们将会学习迭代器和生成器是什么.当然 ...

  3. 【React】Stateless Function

    React创建组件的时候,有3种写法: // 1. 传统写法 const App = React.createClass({}); // 2. es6 的写法 class App extends Re ...

  4. React Native填坑之旅--Stateless组件

    Stateless component也叫无状态组件.有三种方法可以创建无状态组件. 坑 一般一个组件是怎么定义的: 很久以前的方法: const Heading = createClass({ re ...

  5. Python高级特性(1):Iterators、Generators和itertools(参考)

    对数学家来说,Python这门语言有着很多吸引他们的地方.举几个例子:对于tuple.lists以及sets等容器的支持,使用与传统数学类 似的符号标记方式,还有列表推导式这样与数学中集合推导式和集的 ...

  6. STL Iterators

    Summary of Chapter 33 STL Iterators from The C++ Programming Language 4th. Ed., Bjarne Stroustrup. - ...

  7. c++ insert iterators 插入型迭代器

    insert iterators 插入型迭代器 (1)front inserters 前向插入迭代器 只适用于提供有push_front()成员函数的容器,在标准程序库中这样的容器是deque和lis ...

  8. Solve Error Debug Assertion Failed Expression vector iterators incompatible Using PCL in Release Mode of VS2010

    When using PCL 1.4.0 in the release mode building under VS2010, we might sometime get the error &quo ...

  9. 无状态服务(stateless service)

    一.定义 无状态服务(stateless service)对单次请求的处理,不依赖其他请求,也就是说,处理一次请求所需的全部信息,要么都包含在这个请求里,要么可以从外部获取到(比如说数据库),服务器本 ...

随机推荐

  1. 分享10款激发灵感的最新HTML5/CSS3应用

    1.HTML5/CSS3实现iOS Path菜单 菜单动画很酷 Path菜单相信大家都不陌生吧,它在iOS中非常流行,今天我们要分享的菜单就是利用HTML5和CSS3技术来模拟实现这款iOS Path ...

  2. Codevs 1078 ==Poj 1258 Agri-Net

      Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 53270   Accepted: 22140 Description D ...

  3. c++11之右值引用

    本文大部分来自这里,并不是完全着行翻译,如有不明白的地方请参考原文. 在c++中,创建临时对象的开销对程序的影响一直很大,比如以下这个例子: String getName(){ return “Kia ...

  4. bzoj 1042 HAOI2008 硬币购物

    这道题思路是在是神. 先dp出没有限制时候的方案数. dp的时候注意 先循环 1..4 再循环 1..maxs 防止重复.边界是f[0] = 1. 这么基础的背包都忘记了=_= 接下来处理有重复的问题 ...

  5. VS2010使用TeeChart5的ColorGrid绘制一维距离像

    绘制一维距离像原理:使用TeeChart控件中的ColorGrid显示(X,Y,Z)三维数据,X和Z分别代表一维距离像的x轴和y轴数据,Y代表对应的数值,以不同颜色显示. 1.注册TeeChart5 ...

  6. 【风马一族_xml】xmlp之dtd1

    什么是XML约束? 在xml技术里,可以编写一个文档来约束一个xml文档的写法,这称之为xml约束 2. 为什么要使用xml约束? 参看提示栏 3. xml约束的作用? 约束xml的写法 对xml进行 ...

  7. Factory_Method

    class Product { public: virtual ~Product() {} ; }; class ProductA : public Product { public: Product ...

  8. javascript 逻辑运算符

    javascript逻辑运算符 NOT(!) AND(&&) OR(||) NOT(!) 返回值的类型一定是Boolean值的 运算数也是Boolean值 返回值是:与相反的boole ...

  9. 万能的SQLHelper帮助类

    /// <summary> /// 数据库帮助类 /// </summary> public class SQLHelper { private static string c ...

  10. Linq--扩展方法

    如果现在有一个这样的需求,求筛选出来的大于20MB的进程的和,常用的方法是写一个静态方法传进去一个ProcessData列表 比如: public static Int64 TotalMemory( ...