lua按不同深度递归打印嵌套table

目标table:

local a =
{

     {
         "a11",
         "a12",
         "a13"
     },


     {
         "b21",
         "b22",
         "b23"
     },


     {
         "c31",
         "c32",
         "c33",
          ccc = {"cccc"},
          cpt = {"uuuuu"}
     },


     {
           "d12",
           "d13",
         d41 = {123},

         d42 =
                 {
                 moo={456}
                 }
     }
}

函数部分:

local u = 1
local i = 0 ---distance flag
local pp = 0
local cache = {}
local location_cache

local function print_table(arr,flag,distance)

    pp = 0
    u = u+1
    if flag == 1 then

        cache[tostring(arr)] = arr

        for e in pairs(cache) do
            print(tostring(e))
        end

    end

    if u > flag  then

        u=u-1
        return

    end

    if type(arr) == "table" then

        for loc,value in pairs(arr) do

            if type(value) == "table" then

                i = i+1
                if u == flag then
                    print(distance.."  "..loc)
                else
                    print(distance.."  "..loc.." = ".." { ")

                    if pp == 0 then
                        location_cache = distance..string.rep(" ",9)
                        pp = pp+1
                    end

                end

                print_table(value,flag,string.rep(" ",string.len(loc)+u*6))

            else

                print(distance.."  "..tostring(value))

            end

        end

        i = 0

    else

        print(arr)

    end

    u = u-1

    if #tostring(location_cache) > 0 and u ~= 1 then
        print(location_cache.."}")
        location_cache = " "
    end

end

function table_print(arr,flag)

    print_table(arr,flag,"")

end

table_print(a,1)

总结:函数包含2个参数,一个是传入的table,一个是需要打印的深度,这个打印table的递归不难实现,比较坑的地方是打印不同的深度,这一点需要注意,要设置不同的标记符号,每次进入到函数,深度加一,每完整的执行完一次,返回到上一个递归函数时,深度减一,这样可以时刻检查到当前的深度。

执行上面的代码,结果输出如图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值