Lua 迭代器
来源:互联网 发布:js扩展window方法 编辑:程序博客网 时间:2024/05/16 10:42
7.1 Iterators and Closures
In Lua, we typically represent iterators by functions: each time we call the function, it returns the “next” element from the collection.
function values (t) local i =O return function () i = i + 1; return t[i] endend
We can use this iterator in a while loop:
t = {10, 20, 30}iter = values(t) -creates the iteratorwhile true do local element = iter()一一calls the iterator if element == nil then break end print (element)end
however, it is easier to use the generic for.
t = {10, 20, 30}for element in values(t) do print (element)end
function allwords () local line = io.read() -- current line local pos = 1 -- current position in the line return function () -- iterator function while line do -- repeat while there are lines local s, e = string.find(line, "%w+", pos) if s then -- found a word? pos = e + 1 -- next position is after this word return string.sub(line, s, e) -- return the word else line = io.read() -- word not found; try next line pos = 1 -- restart from first position end end return nil -- no more lines: end of traversal endend
0 0
- lua--lua中的迭代器
- Lua 迭代器
- Lua迭代器
- Lua 迭代器
- Lua-迭代器
- Lua 迭代器
- Lua 迭代器
- lua 迭代器
- 迭代器模式lua实现
- Lua iterator 迭代器
- Lua中的迭代器
- lua中的迭代器
- lua 链表 迭代器
- lua自定义迭代器
- Lua 迭代器学习
- lua迭代器原理
- Lua自定义迭代器。
- lua中的迭代器分析
- iOS开发笔记--使用UITextField自动格式化银行卡号
- Python 列表(list) 总结
- 推送
- 读取和设置cookie
- python的range()函数用法
- Lua 迭代器
- 爬虫: 基于Node.js的强大爬虫,能直接发布抓取的文章哦
- VS2013+Windows+opencv3.0.0
- hdu 4143(分解质因数)
- 炫技——加载巨图
- iOS开发笔记--[__NSArrayI addObjectsFromArray:]: unrecognized selector错误
- 图的深度优先遍历
- iOS开发笔记--去掉tableview中section的headerview粘性
- Xshell如何连接Serial