lua中打印table

lua的打印写了一边又一边,我去,每次都要考虑一下,花写时间去写,这个有点,那个啥,扔这里


local string_format = string.format;
local table_insert = table.insert;

function dump_r(t)
    local sp = " ";
    local function do_print(tt, l)
        local tp = type(tt);
        if (tp == "table") then
            l = l + 1;
            if (l - 1 == 0) then
                print("{");
            end
            for k, v in pairs(tt) do
                local pp = type(v);
                if (pp == "table") then
                    print(string_format("%"..l.."s[%s]={",sp,k));
                    do_print(v, l + 1);
                    print(string_format("%"..l.."s},",sp));
                else
                    print(string_format("%"..l.."s[%s]=%s,",sp,k,tostring(v)));
                end

            end
            if (l - 1 == 0) then
                print("}");
            end
        else
            print(string_format("%"..l.."s=%s,",sp,k,tostring(tt)));
        end

    end

    do_print(t, 0);
end

function dump_tostring(t)
    local sp = " ";
    local list = {};
    local function addline(str)
        table_insert(list, str);
    end

    local function do_tostring(tt, l, ln)
        local tp = type(tt);
        if (tp == "table") then
            l = l + 1;
            if (l - 1 == 0) then
                addline("{");
            end
            for k, v in pairs(tt) do
                local pp = type(v);
                if (pp == "table") then
                    addline(string_format("%"..l.."s[%s]={",sp,k));
                    do_tostring(v, l + 1);
                    addline(string_format("%"..l.."s},",sp));
                else
                    addline(string_format("%"..l.."s[%s]=%s,",sp,k,tostring(v)));
                end

            end
            if (l - 1 == 0) then
                addline("}");
            end
        else
            addline(string_format("%"..l.."s=%s,",sp,k,tostring(tt)));
        end

    end

    do_tostring(t, 0);

    return table.concat(list, "\n");
end

local kt = {
    ss = "33";
    mm = "39";
    ks = {
        mk = 36;
        sk = {1,2,3,4,5};
    }
}

print("===========");
--dump_r(kt);
local s = dump_tostring(kt);
print(s);
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值