Lua old-style true iterator

简介:
老版本的Lua不支持for语句, 可以在函数中写循环来达到循环的目的.
以下是书上的例子, 显然函数里面用了for, 所以有点毛病.
> function allwords(f)
>>   for line in io.lines() do
>>     for word in string.gmatch(line, "%w+") do
>>       f(word)
>>     end
>>   end
>> end
-- 调用allwords函数, 使用print函数打印单词
> allwords(print)
hello nihao yes, now no
hello
nihao
yes
now
no

-- allwords传入一个匿名函数, 统计hello出现的次数
> do 
>> local count = 0
>> allwords( function (w) if w == "hello" then count = count +1 end end )
>> print(count)
>> end
hello, nihao, yes, hello
Hello, hello
3


allwords在generic for中的用法, 上一篇文章的例子
2. 使用closure的例子, 将状态值存储在closure中.
factory函数, 返回iterator匿名函数以及state状态值. state封装在iterator匿名函数中.
> function allwords()
>>    local state = {line = io.read(), pos = 1}  -- 使用factory函数的local变量表存储状态值, 对iterator来说就是non-local变量
>>    return function (state)
>>    while state.line do  -- 重复直到最后一行
>>      local s,e = string.find(state.line, "%w+", state.pos)  -- 查找单词
>>      if s then
>>        state.pos = e+1
>>        return string.sub(state.line, s, e)  -- 返回单词
>>      else  -- 否则下一行
>>        state.line = io.read()
>>        state.pos = 1
>>      end
>>    end
>>    return nil  -- 如果没有值, iterator函数返回nil给控制变量, 因此结束generic for循环.
>>  end, state
>> end

> for w in allwords() do
>>  print (w)
>> end
hello nihao a
hello
nihao
a

相关文章
|
6月前
|
Python
python之列表中常用的函数:append,extend,insert,pop,remove,del函数的定义与使用方法,元素是否在列表中的判断
python之列表中常用的函数:append,extend,insert,pop,remove,del函数的定义与使用方法,元素是否在列表中的判断
|
5月前
|
JavaScript
jQuery的empty、remove、detach区别
jQuery的empty、remove、detach区别
|
8月前
|
JavaScript 前端开发
.bezierEasingMixin(); ^ Inline JavaScript is not enabled. Is it set in your op..
.bezierEasingMixin(); ^ Inline JavaScript is not enabled. Is it set in your op..
119 0
|
9月前
|
JavaScript 前端开发
JavaScript:return、return true、return false
JavaScript:return、return true、return false
66 0
|
JavaScript 数据安全/隐私保护 前端开发
js中return,return true,return false三者的用法及区别
return其实就是return undefined; 1.语法及返回方式 ①返回控制与函数结果         语法为:return 表达式;         语句结果函数的执行,返回调用函数,而且把表达式的值作为函数结果返回出去 ②返回控制无函数结果         语法为:return;         在大多数情况下,为事件处理函数如果让其返回false,可以防止默认的事件行为.
1534 0
|
JavaScript 前端开发 Python
JavaScript中Set和Map的基本用法
JavaScript中Set和Map的基本用法
94 0
JavaScript中Set和Map的基本用法
$.extend(true,{},a,b)解析
原文:$.extend(true,{},a,b)解析 版权声明: https://blog.csdn.net/bsfz_2018/article/details/81738437 什么是$.extend jQuery.extend() 函数用于将一个或多个对象的内容合并到目标对象。
879 0
List的Clear方法与RemoveAll方法用法小结
List的Clear方法与RemoveAll方法用法小结http://www.bieryun.com/1055.html 示例代码 [csharp] view plain copy using System; using System.
2318 0