如何在lua中迭代表中的元素对

发布于 2024-12-11 09:11:05 字数 237 浏览 8 评论 0原文

如何在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)

How to iterate over pairs of table elements in lua? I would like to achieve a side-effect free way of circular and non-circular iterating ver pairs.

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

姐不稀罕 2024-12-18 09:11:05

圆形案例的另一种解决方案

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

Another solution for the circular case

   local n=#t
    for i=1,n do 
      print(t[i],t[i%n+1]) 
    end
忆离笙 2024-12-18 09:11:05

这是圆形案例

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)

Here's the circular case

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

Non circular:

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

For fancier output use print(string.format("(%d,%d)",x,y)

给妤﹃绝世温柔 2024-12-18 09:11:05

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

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

How about having no special case for both cases?

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文