博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
迭代器与泛型for
阅读量:7218 次
发布时间:2019-06-29

本文共 1279 字,大约阅读时间需要 4 分钟。

迭代器与closure

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    print("function endddddddddd")    return nil  endendfor word in allwords() do  print(11111)  print(word)end

 无状态的迭代器

local function iter(a,i)  i=i+1  local v=a[i]  if v then     return i,v  endendfunction ipairs(a)--  return iter,a,0 --正确--for获得3个值,迭代器函数,恒定状态,以及控制变量  return iter(a,1) --错误enda={
4,5,6,7}--for k,v in ipairs(a) do -- print(k,v)--endfor k,v in next,a do print(k,v)end

 复杂迭代器

--复杂迭代器,不需要定义局部变量poslocal iteratorfunction allwords()  local state={line=io.read(),pos=1}  return iterator,stateendfunction 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 nilendfor word in allwords() do  print(11111)  print(word)end

 真实迭代器

 

function allwords(f)  for line in io.lines() do    for word in string.gmatch(line,"%w+") do      f(word)    end  endendallwords(print)

 

转载于:https://www.cnblogs.com/ptqueen/p/6763791.html

你可能感兴趣的文章
Java虚拟机笔记(四):垃圾收集器
查看>>
计算机运行命令全集
查看>>
WebSocket 实战
查看>>
二次排序
查看>>
CSS:如何清除a标签之间的默认留白间距
查看>>
selenium随笔
查看>>
leetcode599
查看>>
String类中“==”和“equals()”的区别
查看>>
leetcode--883
查看>>
the application could not be verified
查看>>
[转]Centos配置国内yum源
查看>>
redis数据类型和应用场景
查看>>
Spring IOC
查看>>
Fragment的onCreateView和onActivityCreate之间的区别(转)
查看>>
AC日记——统计难题 hdu 1251
查看>>
在仿真器中运行时跳过Windows Azure Startup任务
查看>>
android 获取路径目录方法以及判断目录是否存在,创建目录
查看>>
数列问题[HAOI2004模拟]
查看>>
2012各大IT公司校招笔试题整理
查看>>
phpcms 后台分页
查看>>