Lua 迭代器
2016-01-27 10:17
337 查看
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.
We can use this iterator in a while loop:
however, it is easier to use the generic for.
In Lua, we typically represent iterators by functions: each time we call the function, it returns the “next” element from the collection.
[code]function values (t) local i =O return function () i = i + 1; return t[i] end end
We can use this iterator in a while loop:
[code]t = {10, 20, 30} iter = values(t) -creates the iterator while 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.
[code]t = {10, 20, 30} for element in values(t) do print (element) end
[code]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 end end
相关文章推荐
- Lua按指定字符分隔字符串的3种方法
- 初识 love2d. Hello World & lua 调试 & iOS 环境运行
- 使用lua代码创建文件夹,解压zip文件到指定目录(亲测可用)
- lua io函数
- lua os函数
- lua table函数
- lua重要函数
- Lua string函数说明
- lua 字符串模式匹配
- 为什么 Lua 的新版本越来越慢?
- LUAMD5加密
- LUAMD5加密
- Lua学习笔记(函数)
- lua与游戏测试(二)
- lua 与游戏测试 (一)
- lua的table库中经常使用的函数
- lua之m进制转换为n进制-任意进制转换算法
- quicklua随机数
- 机器学习模型评价(Evaluating Machine Learning Models)-主要概念与陷阱
- Leetcode 150. Evaluate Reverse Polish Notation