You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lua中递归构建未知数量列表的嵌套表结构

递归构建Lua多层嵌套表结构

我有若干个Lua列表,示例如下:

local first =  {"ship", "truck"}
local second =  {"container", "crate"}
local third = {"box", "bag", "case"}
local fourth =  {"apple", "banana"}

需要构建一个嵌套表结构,每个列表的元素都包含下一个列表的所有元素,以此类推。目前已经实现了处理两个列表的函数:

local function do_it(list_1, list_2)
    local toplevel = {}
    for _, item_1 in pairs(list_1) do
        toplevel[item_1] = {}
        for _, item_2 in pairs(list_2) do
            table.insert(toplevel[item_1], item_2)
        end
    end
    return toplevel
end

该函数返回结果:

truck:
  1: container
  2: crate
ship:
  1: container
  2: crate

但不知道如何通过递归实现多列表的嵌套构建,期望得到如下层级结构:

truck:
  1: container
    1: box
      1: apple
      2: banana
    2: bag
      1: apple
      2: banana
    3: case
      1: apple
      2: banana
  2: crate
    1: box
      1: apple
      2: banana
    2: bag
      1: apple
      2: banana
    3: case
      1: apple
      2: banana
ship:
  1: container
    1: box
      1: apple
      2: banana
    2: bag
      1: apple
      2: banana
    3: case
      1: apple
      2: banana
  2: crate
    1: box
      1: apple
      2: banana
    2: bag
      1: apple
      2: banana
    3: case
      1: apple
      2: banana

递归实现方案

要处理任意数量的列表,递归是最简洁的方式,核心思路:

  • 终止条件:当只剩一个列表时,直接返回该列表的元素作为最底层的叶子节点
  • 递归逻辑:取第一个列表的每个元素,为每个元素递归构建其下一层的嵌套结构

代码实现:

local function build_nested(...)
    local lists = {...}
    -- 递归终止:只剩一个列表,返回其元素
    if #lists == 1 then
        return lists[1]
    end
    -- 取出第一个列表,剩余列表作为后续层级
    local current_list = table.remove(lists, 1)
    local result = {}
    for _, item in ipairs(current_list) do
        -- 递归生成当前元素的下一层结构
        result[item] = build_nested(unpack(lists))
    end
    return result
end

使用方法

调用函数时传入所有需要嵌套的列表即可:

local nested_table = build_nested(first, second, third, fourth)

验证输出结构

可以用以下打印函数来可视化嵌套结构:

local function print_nested(tbl, indent)
    indent = indent or 0
    local prefix = string.rep("  ", indent)
    for key, value in pairs(tbl) do
        print(prefix .. tostring(key) .. ":")
        if type(value) == "table" then
            print_nested(value, indent + 1)
        else
            print(prefix .. "  " .. tostring(value))
        end
    end
end

-- 打印结果
print_nested(nested_table)

运行后会输出符合预期的多层嵌套结构。


内容的提问来源于stack exchange,提问作者applepie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:15:36