closure
能够保存迭代器所需保存的全部状态table
并保存在 恒定状态中 table
table
的内容却能够改变即在循环过程当中改变 table
数据local iterator function allwords() local state = {line = io.read(), pos = 1} return iterator, state end function iterator(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 end
错误记录
io.read
,而不是函数调用 io.read()
bad argument #1 to 'find' (string expected, got function)
string
类型,实际上获得的确实 function
类型string.find(state.line, ...)
其中的 第一个参数已经为 function
类型了,因此循环结束io.read()
用户输入任何东西都会为 string
类型io.read("*number")
这样就指定用户输入为 number
类型了for
变量中closure
实现的 table
比一个使用 table
的迭代器高效table
快 for
循环function allwords(f) for line in io.read() do -- gmatch 匹配全部符合模式的字符串 for word in string.gmatch(line, "%w+") do f(word) end end end allwords(print) local count = 0 allwords(function(w) if w == "hello" then count = count + 1 end end ) print(count) local count = 0 for w in allwords() do if w == "hello" then count = count + 1 end end print(count)
生成器容许两个或多个并行的迭代过程git
break
和 return
语句