lua打印table

在调试lua代码的时候,经常需要看table里的内容,这时候一般都是将打印table的方法放到工具模块中,方便调用。
现在写一个简单的工具模块
util.lua

local util = {}

local function get_type_first_print( t )
    local str = type(t)
    return string.upper(string.sub(str, 1, 1))..":"
end

function util.dump_table(t, prefix, indent_input, print)
    local indent = indent_input
    if indent_input == nil then
        indent = 1
    end

    if print == nil then
        print = _G["print"]
    end

    local p = nil

    local formatting = string.rep("    ", indent)
    if prefix ~= nil then
        formatting = prefix .. formatting
    end

    if t == nil then
        print(formatting.." nil")
        return
    end

    if type(t) ~= "table" then
        print(formatting..get_type_first_print(t)..tostring(t))
        return
    end

    local output_count = 0
    for k,v in pairs(t) do
        local str_k = get_type_first_print(k)
        if type(v) == "table" then

            print(formatting..str_k..k.." -> ")

            util.dump_table(v, prefix, indent + 1,print)
        else
            print(formatting..str_k..k.." -> ".. get_type_first_print(v)..tostring(v))
        end
        output_count = output_count + 1
    end

    if output_count == 0 then
        print(formatting.." {}")
    end
end

return util

测试代码:

local util = require "util"

--_G["print"] = function () end

local testTable = {"hello", "world", ["first"] = 1, ["second"] = 2}

util.dump_table(testTable, "--testTable")

输出结果:

--testTable    N:1 -> S:hello
--testTable    N:2 -> S:world
--testTable    S:first -> N:1
--testTable    S:second -> N:2

如果最后一行改成:

util.dump_table(testTable)

则输出:

    N:1 -> S:hello
    N:2 -> S:world
    S:first -> N:1
    S:second -> N:2

有注意到,前面的大写字母N表示number,S表示string类型,依次类推,取类型的第一个字母(大写)表示类型。
有注意到注释中:

--_G["print"] = function () end

如果把这句前面的注释去掉,则util.dump_table什么也不会输出,这样的好处就是控制了工程中所有的print,相当于一个开关,方便上线的时候直接屏蔽print,而开发时候,又可以打开print。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值