【问题标题】:How to iterate over pairs of elements in table in lua如何在lua中迭代表中的元素对
【发布时间】:2011-12-14 07:35:03
【问题描述】:

如何在 lua 中迭代成对的表格元素?我想实现一种无副作用的循环和非循环迭代版本对。

I have table like this:
t = {1,2,3,4}

Desired output of non-circular iteration:
(1,2)
(2,3)
(3,4)

Desired output of circular iteration:
(1,2)
(2,3)
(3,4)
(4,1)

【问题讨论】:

    标签: loops lua lua-table


    【解决方案1】:

    圆形情况的另一种解决方案

       local n=#t
        for i=1,n do 
          print(t[i],t[i%n+1]) 
        end
    

    【讨论】:

      【解决方案2】:

      这是圆形盒子

      for i = 1, #t do 
        local a,b
        a = t[i]
        if i == #t then b = t[1] else b = t[i+1] end 
        print(a,b) 
      end
      

      非循环:

      for i = 1, #t-1 do 
        print(t[i],t[i+1]) 
      end
      

      对于更高级的输出,请使用print(string.format("(%d,%d)",x,y)

      【讨论】:

        【解决方案3】:

        两种情况都没有特殊情况怎么样?

        function print_pair(x, y)
           local s = string.format("(%d, %d)", x, y)
           print(s)
        end
        
        function print_pairs(t)
           for i = 1, #t - 1 do
              print_pair(t[i], t[i + 1])
           end
        end
        
        function print_pairs_circular(t)
           print_pairs(t)
           print_pair(t[#t], t[1])
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-02-26
          • 1970-01-01
          • 1970-01-01
          • 2018-02-02
          • 2018-07-22
          • 1970-01-01
          • 2017-12-08
          相关资源
          最近更新 更多