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)对单次请求的处理,不依赖其他请求,也就是说,处理一次请求所需的全部信息,要么都包含在这个请求里,要么可以从外部获取到(比如说数据库),服务器本 ...
随机推荐
- While readingiphone真机无法显示图片,而模拟器可以正常显示
可能,很多开发IOS程序的遇到过在模拟器里,加载图片都是正常的,但是在真机里就会出现图片资源不能加载的问题. 其中一种原因是,在Simulator里面,例如:图片资源名称为:a.PNG,在代码你里,你 ...
- UINavigationController的popViewControllerAnimated问题
UINavigationController是IOS编程中的一个view controller的容器,通过栈管理viewControllers,每一次push操作都将在栈顶添加一个view contr ...
- ☆RHEL6创建软raid的使用☆——经典之作
raid主要的种类 1.raid0 扩展卷 raid 0又称Stripee或Striping,中文译为集带工作方式, 有时也可以理解为拼凑. 它是将要存取的数据以条带状的形式尽量平均分配到多个硬 ...
- SQL联合查询中的关键语法(转)
联合查询效率较高.以下例子来说明联合查询的好处 t1表结构(用户名,密码) userid int username varchar(20) password ...
- Java 多线程的基本概念
一.线程介绍 多线程同时运行时,单CPU系统实际上是分给每个线程固定的时间片,用这种方式使得线程“看起来像是并行的”.在多CPU系统中,每个CPU可以单独运行一个线程,实现真正意义上的并行,但是如果线 ...
- 打造自己的3D全景漫游
three.js 示例: 打造H5里的"3D全景漫游"秘籍 - 腾讯ISUX QQ物联星球计划 通过pano2vr直接将鱼眼全景图生成立体空间的六个面:也可通过Photos ...
- jquery实现ajax,返回json数据
jquery实现ajax可以调用几种方法 我经常用的是$get(url,data,callback,type)方法 其中url是异步请求的页面(可以是.ashx文件),data是参数,callback ...
- 客户端访问WebService和PageMethod
客户端访问WebService 客户端访问WebService和后台访问WebService没什么不同,注意的地方是要在ScriptManager中添加 <Services> ...
- nginx服务器绑定域名和设置根目录
首先进入nginx安装目录的配置目录conf,然后执行 vi conf/nginx.conf 打开nginx的配置文件,找到并修改红字部分 server { listen default_server ...
- Andriod wifi 基本操作
从用户角度看,Android Wi-Fi模块自下向上可以看为5层:硬件驱动程序,wpa_suppplicant,JNI,WiFi API,WifiSettings应用程序. 1.wpa_supplic ...