zoukankan      html  css  js  c++  java
  • 写一个可以用的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,"	")
                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," {
    ")
            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,"
    ")
                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," }
    ")
        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))
    

      

    以上。

  • 相关阅读:
    配置Kickstart无人值守安装centos5.9 天高地厚
    数据库是什么,它是做什么用的? 天高地厚
    Mysql主从复制 天高地厚
    android开发中eclipse里xml的自动提示
    "error: device not found" and "error:device offline"
    gentoo中emerge失效:File "/usr/bin/emerge", line 43
    android:修改preference中view属性
    gerrit上利用sshkeygen公钥
    git 基本命令介绍
    prebuilt/linuxx86/toolchain/armeabi4.4.3/bin/armeabigcc: /lib/libc.so.6: version `GLIBC_2.11' not found:解决办法
  • 原文地址:https://www.cnblogs.com/fastcam/p/14987462.html
Copyright © 2011-2022 走看看