Stateless Iterators
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 next, t, 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的更多相关文章
- lua自定义迭代器
迭代器 http://www.tutorialspoint.com/lua/lua_iterators.htm 迭代器能够让你遍历某个集合或者容器中的每一个元素. 对于lua来说, 集合通常指代 ta ...
- Python标准模块--Iterators和Generators
1 模块简介 当你开始使用Python编程时,你或许已经使用了iterators(迭代器)和generators(生成器),你当时可能并没有意识到.在本篇博文中,我们将会学习迭代器和生成器是什么.当然 ...
- 【React】Stateless Function
React创建组件的时候,有3种写法: // 1. 传统写法 const App = React.createClass({}); // 2. es6 的写法 class App extends Re ...
- React Native填坑之旅--Stateless组件
Stateless component也叫无状态组件.有三种方法可以创建无状态组件. 坑 一般一个组件是怎么定义的: 很久以前的方法: const Heading = createClass({ re ...
- Python高级特性(1):Iterators、Generators和itertools(参考)
对数学家来说,Python这门语言有着很多吸引他们的地方.举几个例子:对于tuple.lists以及sets等容器的支持,使用与传统数学类 似的符号标记方式,还有列表推导式这样与数学中集合推导式和集的 ...
- STL Iterators
Summary of Chapter 33 STL Iterators from The C++ Programming Language 4th. Ed., Bjarne Stroustrup. - ...
- c++ insert iterators 插入型迭代器
insert iterators 插入型迭代器 (1)front inserters 前向插入迭代器 只适用于提供有push_front()成员函数的容器,在标准程序库中这样的容器是deque和lis ...
- 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 ...
- 无状态服务(stateless service)
一.定义 无状态服务(stateless service)对单次请求的处理,不依赖其他请求,也就是说,处理一次请求所需的全部信息,要么都包含在这个请求里,要么可以从外部获取到(比如说数据库),服务器本 ...
随机推荐
- 推荐7款新鲜出炉的HTML5/CSS3应用
1.HTML5/CSS3发光文字可自定义文字色彩效果很赞 要分享的这款HTML5/CSS3文字效果很帅,鼠标滑过文字时,文字会出现发光的特效,并且我们可以自定义文字和颜色. 在线演示 源码下载 2.H ...
- [Guava学习笔记]Strings: 字符串处理
我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3861502.html,享受整齐的排版.有效的链接.正确的代码缩进.更好的阅读体验 ...
- android activity空指针异常解决问题解决
今天在开发过程中,遇到了一个错误 unable to instantiate activity componentinfo java.lang.nullpointerexception google之 ...
- 《openstack 和hadoop的区别是什么?》
openstack 和hadoop的区别是什么? (一) openstack仿照的Amazon的云,hadoop仿照的是Google的云 openstack注重的是虚拟化/虚拟机及其配套的服务,had ...
- 《搭建DNS负载均衡服务》RHEL6
搭建DNS负载均衡环境: 1.至少三台的linux虚拟机,一台主的DNS服务器,1台副的(可以N台),1台测试机. 负载均衡有很多种,apache那样的是为了缓解人们访问网站时给服务器造成太大的压力, ...
- [react native] Error loading page
如上图显示的错误,解决方法如下: 在react native ios项目的info.plist文件中,新增一个属性. 在Info.plist中添加NSAppTransportSecurity类型Dic ...
- NodeJs菜鸟初始
我们先来了解下什么是nodejs 一.nodejs具有事件驱动.异步编程的特点. 事件驱动这个词并不陌生,在某些传统语言的网络编程中,我们会用到回调函数,比如当socket资源达到某种状态时,注册的回 ...
- JAVA四种线程池实例
1.new Thread的弊端 执行一个异步任务你还只是如下new Thread吗? Java 1 2 3 4 5 6 7 new Thread(new Runnable() { ...
- 使用自定义的item、Adapter和AsyncTask、第三方开源框架PullToRefresh联合使用实现自定义的下拉列表(从网络加载图片显示在item中的ImageView)
AsyncTask使用方法详情:http://www.cnblogs.com/zzw1994/p/4959949.html 下拉开源框架PullToRefresh使用方法和下载详情:http://ww ...
- 金融系列4《PUTKEY指令》
用一个新的密钥替换一个已经存在的密钥:新密钥可以有与被替换的密钥相同的或不同的密钥版本号,但是必须与被替换的密钥有相同的密钥标识符. 用新密钥替换多个已经存在的密钥:新密钥可以有与被替换的密钥相同的或 ...