对lua泛型for迭代器一些理解

1.w3cschool菜鸟教程中提到:泛型 for 在自己内部保存迭代函数,实际上它保存三个值:迭代函数、状态常量、控制变量。

 

[plain] view plain copy 在CODE上查看代码片派生到我的代码片
  1. --以下为无状态迭代器  
  2. function square(iteratorMaxCount,currentNumber)  
  3.    if currentNumber<iteratorMaxCount  
  4.    then  
  5.       currentNumber = currentNumber+1  
  6.    return currentNumber, currentNumber*currentNumber  
  7.    end  
  8. end  
  9.   
  10. --泛型 for 在自己内部保存迭代函数,实际上它保存三个值:  
  11. --迭代函数square、状态常量3、控制变量0  
  12. for i,n in square,3,0 do  
  13.    print(i,n)  
  14. end  

理解看后面总结

2.对于多状态迭代器

 

[plain] view plain copy 在CODE上查看代码片派生到我的代码片
  1. --多状态迭代器  
  2. function elementIterator (collection)  
  3.    local index = 0  
  4.    local count = #collection  
  5.    -- 闭包函数  
  6.    return function ()  
  7.       index = index + 1  
  8.       if index <= count  
  9.       then  
  10.          --  返回迭代器的当前元素  
  11.          return collection[index]  
  12.       end  
  13.    end  
  14. end  
  15.   
  16.   
  17. for v in elementIterator({11,22,33}) do  
  18.     print(v)  
  19. end  

理解看后面总结

3.自定义ipais

 

[plain] view plain copy 在CODE上查看代码片派生到我的代码片
  1. function iter (a, i)  
  2.     i = i + 1  
  3.     local v = a[i]  
  4.     if v then  
  5.        return i, v  
  6.     end  
  7. end  
  8.   
  9. function ipairs (a)  
  10.     return iter, a, 0  
  11. end  
  12.   
  13. for i,v in ipairs({111,222,333}) do  
  14.     print(i,v)  
  15. end  

理解看下


综上总结一下:

1.我们先理解 for 语句的 意思

for ...(1) in func(2) ...(3) do

end

...(1) 是每次执行参数为...(3)的函数func(2)的返回值,直到返回nil,也就是...(1)整体为nil值时,循环结束 

例子

[plain] view plain copy 在CODE上查看代码片派生到我的代码片
  1. local a = 0  
  2. local function pa(b,c)  
  3.     a = a + 1  
  4.     if a < 5 then  
  5.         return 1,2,3,a  
  6.     else  
  7.         return nil  
  8.     end  
  9. end  
  10. for i,j,k,v in pa,1,1 do  
  11.     print(i,j,k,v)  
  12. end  

2.理解了for的语义,我们再回头看下例子2

for v in elementIterator({11,22,33}) do
    print(v)
end

每次执行elementIterator({11,22,33})的返回值函数(注意,这里是执行elementIterator的返回值(一个函数),并不是执行elementIterator):

也就是每次执行函数

function ()
      index = index + 1
      if index <= count
      then
         --  返回迭代器的当前元素
         return collection[index]
      end
end
该函数携带参数无,并且可以访问到elementIterator的局部参数   local index = 0  local count = #collection,其返回一个table中的元素,并且存到v中

3.对于例子1 这理解就简单多了

for 循环中 每次执行square函数,该函数携带两个参数iteratorMaxCount,currentNumber,初始化分别为3,0

函数返回两个值分别存到i,v中,直到返回整体为nil,循环结束

4.例子3,其实和例子1大同小异,ipairs (a) 其实是把函数itera,以及itera的参数a,i封装起来了

for i,v in ipairs({111,222,333}) do 等价于

for i,v in iter,{111,222,333}, 0 do
5.再点一个,不别太在意 状态常量、控制变量 是什么意思,他们只是迭代函数的参数而已,并且这参数个数可有可无,可多可少,并非就一定得是(状态常量、控制变量)你两个而已

posted @ 2017-02-16 20:51  何人之名  阅读(178)  评论(0)    收藏  举报