Lua语言迭代器示例1
2015-06-11 18:36
495 查看
所谓“迭代器"(Iterator)就是一种可以遍历(iterate over)一种集合中所有元素的机制。
1、首先创建一个.lua文件,向其中输入:
function allwords()
local line=io.read()
local pos=1
return function()
while line do
local s,e=string.find(line,"%w+",pos)
if s then
pos=e+1
return string.sub(line,s,e)
else
line=io.read()
pos=1
end
end
return nil
end
end
for word in allwords() do
print(word)
end
2、用lua解释器执行该脚本:
由上例可知,迭代器虽然编写比较麻烦,但是调用迭代器时,非常简便,这就是迭代器的好处。
所谓“迭代器"(Iterator)就是一种可以遍历(iterate over)一种集合中所有元素的机制。
1、首先创建一个.lua文件,向其中输入:
function allwords()
local line=io.read()
local pos=1
return function()
while line do
local s,e=string.find(line,"%w+",pos)
if s then
pos=e+1
return string.sub(line,s,e)
else
line=io.read()
pos=1
end
end
return nil
end
end
for word in allwords() do
print(word)
end
2、用lua解释器执行该脚本:
由上例可知,迭代器虽然编写比较麻烦,但是调用迭代器时,非常简便,这就是迭代器的好处。
相关文章推荐
- Lua中的table函数库
- lua -- encode and decode
- lua关于require和package.loaded 之间的关系
- 纯lua版A*算法优化测试
- sublime lua环境配置
- lua 匹配
- Lua 基础 -- 学习笔记
- Lua 中使用面向对象(续)
- Lua 的 私有性
- 为什么 Lua 的新版本越来越慢?
- luaJIT FFI Library
- lua 字符串过滤,特殊字符过滤
- MAC中sublime text 编译 Lua
- Lua中table.sort() 报错 attempt to compare number with nil和invalid order function for sorting
- lua运算符优先级
- Xcode6中lua生成静态库
- lua优化建议
- Lua模式匹配
- Lua学习 1) —— Android呼叫变量值和分配
- lua不支持thrift协议