Sunday, May 13, 2012

Lua의 closure 이용해 array iterator 만든 예

 function array_iterator(a, startIndex, endIndex)  
      local i = startIndex - 1  
      return function()  
           i = i + 1  
           if (i > endIndex) then   
                return nil  
           else   
                if (i <= #a) then   
                     return i, a[i]  
                end  
           end  
      end  
 end  
 local a = {"Ariel", "Betty", "Clara"}  
 for i, v in array_iterator(a, 1, 3) do  
      print(i, v)  
 end  
   

No comments:

Post a Comment