首页 > 代码库 > Lua打印table树形结构

Lua打印table树形结构

 1 module(..., package.seeall) 2  3 local g_Debug_Flag = true 4  5 function log(msg) 6     if g_Debug_Flag == false then 7         return 8     end 9     cclog(msg)10 end11 12 ---13 --@function  dump()14 --@param value table 需要打印的15 --@param description string 描述16 --@param nesting int table嵌套层级17 --@end18 19 function dump(value, description, nesting)20     if g_Debug_Flag == false then21         return22     end23 24     --默认打印层级325     if type(nesting) ~= "number" then26         nesting = 327     end28 29     local lookupTable = {}30     local result =  {}31 32     local function _v(v)33         if type(v) == "string" then34             v = "\"" .. v .. "\""35         end36         return tostring(v)37     end38 39     local function _dump(value, description, indent, nest, keylen)40         description = description or "<var>"41         spc = ""42         if type(keylen) == "number" then43             spc = string.rep(" ",keylen - string.len(_v(description)))44         end45 46         if type(value) ~= "table" then47             result[#result + 1] = string.format("%s%s%s = %s", indent, _v(description), spc, _v(value))48         elseif lookupTable[value] then49             result[#result + 1] = string.format("%s%s%s = *REF*", indent, description, spc)50         else51             lookupTable[value] = true52             if nest > nesting then53                 result[#result + 1] = string.format("%s%s = *MAX NESTING*", indent, description)54             else55                 result[#result + 1] = string.format("%s%s = {" , indent, _v(description))56                 local indent2 = indent .. "    "57                 local keys = {}58                 local keylen = 059                 local values = {}60                 for k, v in pairs(value) do61                     keys[#keys + 1] = k62                     local vk = _v(k)63                     local vk1 = string.len(vk)64                     if vk1 > keylen then65                         keylen = vk166                     end67                     values[k] = v68                 end69                 table.sort(keys,function(a, b)70                     if type(a) == "number" and type(b) == "number" then71                         return a < b72                     else73                         return tostring(a) < tostring(b)74                     end75                 end)76 77                 for i, k in pairs(keys) do78                     _dump(values[k], k, indent2,nest + 1,keylen)79                 end80                 result[#result + 1] = string.format("%s}", indent)81             end82         end83     end84     _dump(value,description, "- ", 1)85 86     for i, line in pairs(result) do87         print(line)88     end89 90 end

 

Lua打印table树形结构