写一个可以用的Lua打印Table的函数

function PrintTable(node)
    if not node or type(node) ~= "table" then
        return tostring(node)
    end
    local depthBufferHelper = {}
    local function tab(amt)
        if not depthBufferHelper[amt] then
            local t = {}
            for i = 1, amt do
                table.insert(t,"\t")
            end
            depthBufferHelper[amt] = table.concat(t)
        end
        return depthBufferHelper[amt]
    end
    local bufferHelper = {}
    local function __P(_node,_depth,_buffer)
        bufferHelper[_node] = true
        table.insert(_buffer,tab(_depth-1))
        table.insert(_buffer," {\n")
        for k,v in pairs(_node)  do
            local output = {}
            table.insert(output,tab(_depth))
            if (type(k) == "number" or type(k) == "boolean") then
                table.insert(output,"[")
                table.insert(output,tostring(k))
                table.insert(output,"]")
            else
                table.insert(output,"['")
                table.insert(output,tostring(k))
                table.insert(output,"']")
            end

            table.insert(output," = ")
            table.insert(output,tostring(v))
            table.insert(output,"\n")
            table.insert(_buffer,table.concat(output))
            if (type(v) == "table") then
                if bufferHelper[v] == nil then
                    __P(v,_depth + 1,_buffer)
                end
            end
        end
        table.insert(_buffer,tab(_depth-1))
        table.insert(_buffer," }\n")
    end

    local depth = 1
    local buffer = {}
    __P(node,depth,buffer)
    return table.concat(buffer)
end

  

这个函数会拼一个字符串,并不是真的print什么东西,所以吐槽名字的,嗯,我知道……

但是用还是可以用的,换上你们熟悉的名字,加个debug.traceback什么的在log里算是比较OK了。

其实写Lua已经很长时间了,也奇怪网上为什么都是不能用的打印函数。因为都是菜鸡?

还是大家都喜欢调试而不喜欢用log?关键调试和log应用场景也不一样啊。

对了,这个函数格式化出来会像这样:

看出来了么?第二个打印出来的table里有循环引用。这也是我为什么说没看到有好用的函数的原因,

不是循环引用没处理,就是处理了循环引用,但字符串格式崩了。

循环引用的测试代码长这样:

local t1 = {}
local t2 = {}
local t3 = {}
t1.next = t2
t2.next = t3
t3.next = t2
print(PrintTable(t1))

  

以上。

posted on 2021-07-08 18:05  毛尹航  阅读(560)  评论(0编辑  收藏  举报