天天看點

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
           

如果最後一行改成:

則輸出:

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。

繼續閱讀