将一张表分成多个数组,每 X 个元素

发布于 2025-01-15 21:59:54 字数 285 浏览 0 评论 0原文

假设我有一个表,我想将它细分为每个 X 元素

fruits = {"banana","orange","apple","avocado","cherry","coconut"}

 -- Split every 2 elements independent of array size

fruits = {{"banana","orange"},{"apple","avodado"},{"cherry","coconut"}}

suppose i have one table, and i want do subdivide it every X elements

fruits = {"banana","orange","apple","avocado","cherry","coconut"}

 -- Split every 2 elements independent of array size

fruits = {{"banana","orange"},{"apple","avodado"},{"cherry","coconut"}}

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

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

发布评论

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

评论(1

蓝颜夕 2025-01-22 21:59:54

使用两个 for 循环,步长为 x

local function splitx(tbl, x)
  assert(x > 0)
  assert(type(tbl) == "table")
  local result = {}
  for i=1,#tbl,x do
    local item = {}
    for j=i,i+x-1 do
      if tbl[j] then
        table.insert(item, tbl[j])
      end
    end
    table.insert(result, item)
  end
  return result
end

use two for loop with step of x

local function splitx(tbl, x)
  assert(x > 0)
  assert(type(tbl) == "table")
  local result = {}
  for i=1,#tbl,x do
    local item = {}
    for j=i,i+x-1 do
      if tbl[j] then
        table.insert(item, tbl[j])
      end
    end
    table.insert(result, item)
  end
  return result
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文