• 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的语义

  • 相关阅读:
    h5 . css入门 2.CSS基础
    html5与css 1. web标准及组成
    SQL编程
    JMeter学习(八)JDBC测试计划-连接Oracle
    JMeter学习(七)聚合报告之 90% Line 正确理解
    JMeter学习(六)集合点
    JMeter学习(五)检查点
    JMeter学习(十四)jmeter_断言使用
    JMeter学习(四)参数化
    JMeter学习(三)元件的作用域与执行顺序
  • 原文地址:https://www.cnblogs.com/jackStudy/p/4429667.html
Copyright © 2020-2023  润新知