zoukankan      html  css  js  c++  java
  • lua 高级篇(二)

    第七章  迭代器与泛型for

          迭代器是一种支持指针类型的结构,它可以遍历集合的每一个元素,在Lua中我们常常使用函数来描述迭代器,每次调用该函数就返回集合的下一个元素。

       一、迭代器与闭包

       一个简单的例子: 我们为一个list写一个简单的迭代器,与ipairs()不同的是我们实现的这个迭代器返回元素的值而不是索引下标:

    function list_iter(t)
        local i = 0
        local n = table.getn(t)
        return function ()
            i =  i + 1
            if i <= n then
                return t[i]
            end
        end
    end
    
    t = {10,20,30}
    iter = list_iter(t) -- cerates the iterator
    
    while true do
        local element = iter() -- calls the iterator
        if element == nil then
            break
        end
        print(element)
    end

            下面看一个稍微高级一点的例子:我们写一个迭代器遍历一个文件内的所有匹配的单词。为了实现目的,我们需要保留两个值:当前行和在当前行的偏移量,我们使用两个外部局部变量line、pos保存这两个值。

    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 foud; try next line
                    pos = 1           -- restart from first position
                end
            end
        return nil  -- no more lines: end of travelsal
        end
    end
    
    for word in allwords() do
        print(word)
    end

      二、范性for的语义

  • 相关阅读:
    没人关注的角落是个好地方
    PICKIT3 WIN10 无法连接问题解决
    TM1650+msp430单片机 调试及遇到问题的总结
    即将会来日常更新stm32的学习过程
    Learn Arduino the hard way 1——点亮一个LED
    准备再次开始更新
    Tcl之Read files for synthesis
    Verilog之event
    Tcl之Math
    Digital design之Boolean Algebra
  • 原文地址:https://www.cnblogs.com/jackStudy/p/4429667.html
Copyright © 2011-2022 走看看