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)对单次请求的处理,不依赖其他请求,也就是说,处理一次请求所需的全部信息,要么都包含在这个请求里,要么可以从外部获取到(比如说数据库),服务器本 ...
随机推荐
- struts2,hibernate4,spring3配置时问题汇总及解决办法
文章转载于wanglihu的博客,原文链接http://wanglihu.iteye.com/blog/1897718 1.java.lang.NoClassDefFoundError: org/ob ...
- codevs 3185 队列练习1
题目描述 Description 给定一个队列(初始为空),只有两种操作入队和出队,现给出这些操作请输出最终的队头元素. 操作解释:1表示入队,2表示出队 输入描述 Input Description ...
- grep恢复误删除文件内容(转)
在 Linux 上如果事先没有用别名(alias)修改默认的 rm 功能,rm 后文件就会丢失,幸运的是,在一般的删除文件操作中,Linux 并不会立即清空存储该文件的 block 内容,而只会释放该 ...
- Visual Studio 2013密钥
Visual Studio 2013旗舰版KEY:BWG7X-J98B3-W34RT-33B3R-JVYW9Ultimate:BWG7X-J98B3-W34RT-33B3R-JVYW9 Premium ...
- Window 8.1 计时器功能及图片切换
<Canvas Margin="450,0" Width="795" Grid.Column="1"> <Image Ma ...
- Java IO流详尽解析
流的概念和作用 学习Java IO,不得不提到的就是JavaIO流. 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输 ...
- Amazon S3 PHP Class Documentation
API : http://undesigned.org.za/2007/10/22/amazon-s3-php-class/documentation Example: http://www.phpb ...
- js阻止冒泡事件及默认操作
1. 事件目标 现在,事件处理程序中的变量event保存着事件对象.而event.target属性保存着发生事件的目标元素.这个属性是DOM API中规定的,但是没有被所有浏览器实现 .jQuery对 ...
- openerp 经典收藏 通过view实现字段的只读、隐藏操作(转载)
通过view实现字段的只读.隐藏操作 原文地址:http://cn.openerp.cn/view_groups/ 在OpenERP V7视图(ir.ui.view)多了一个非常有用的字段(group ...
- Java 图形编程 一:入门
package second; import java.awt.Color; import java.awt.Frame; import java.awt.event.WindowAdapter; i ...