【ulua入门】log(打印)lua中的table数据

来源:互联网 发布:绣花制版软件 编辑:程序博客网 时间:2024/06/07 06:05


先上代码:


local function dump_value_(v)    if type(v) == "string" then        v = "\"" .. v .. "\""    end    return tostring(v)end-- 主要用于显示表格, 表格,标识,显示表格的深度,默认3级function PrintTable(value, desciption, nesting, show_meta)    if type(nesting) ~= "number" then nesting = 3 end    show_meta = show_meta or false    local lookupTable = {}    local result = {}    local traceback = string.split(debug.traceback("", 2), "\n")    --print("dump from: " .. string.trim(traceback[3]))    local function dump_(value, desciption, indent, nest, keylen)        desciption =" <color=#FF00FF> ".. desciption.."</color>" or "<color=#bb5555> <table> </color>"        local spc = ""        if type(keylen) == "number" then            spc = string.rep(" ", keylen - string.len(dump_value_(desciption)))        end        if type(value) ~= "table" then            result[#result +1 ] = string.format("%s%s%s = %s", indent, dump_value_(desciption), spc, dump_value_(value))        elseif lookupTable[tostring(value)] then            result[#result +1 ] = string.format("%s%s%s = *REF*", indent, dump_value_(desciption), spc)        else            lookupTable[tostring(value)] = true            if nest > nesting then                result[#result +1 ] = string.format("%s%s = *MAX NESTING*", indent, dump_value_(desciption))            else                result[#result +1 ] = string.format("%s%s = {", indent, dump_value_(desciption))                local indent2 = indent.."    "                local keys = {}                local keylen = 0                local values = {}                for k, v in pairs(value) do                    keys[#keys + 1] = k                    local vk = dump_value_(k)                    local vkl = string.len(vk)                    if vkl > keylen then keylen = vkl end                    values[k] = v                end                table.sort(keys, function(a, b)                    if type(a) == "number" and type(b) == "number" then                        return a < b                    else                        return tostring(a) < tostring(b)                    end                end)                for i, k in ipairs(keys) do                    dump_(values[k], k, indent2, nest + 1, keylen)                end                result[#result +1] = string.format("%s}", indent)            end        end    end    dump_(value, desciption, "\n", 1)    local outStr="";    for i, line in ipairs(result) do        outStr = outStr..line    end    log(outStr)    return outStrend


测试代码:

    local testTable = {}    for i=1,10 do        testTable[i] = i * 10 + 5    end    --第一个参数传入table,第二个参数为这个table的别名    PrintTable(testTable, "TestTableValue")

输出效果图: