Lua打印table树形结构

--这是quick中的工具,作用就是打印Lua中强大的table的结构, 当table的嵌套层级比较多的时候,这个工具非常方便,开发中必备的工具。
--具体使用方法:local debug = require("debug")
--       debug.dump(dataTable, "dataTable", 3) 接下来就可以在控制台看到输出的结果了,非常漂亮的树形结构

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 end 11 12 --- 13 --@function dump() 14 --@param value table 需要打印的 15 --@param description string 描述 16 --@param nesting int table嵌套层级 17 --@end 18 19 function dump(value, description, nesting) 20 if g_Debug_Flag == false then 21 return 22 end 23 24 --默认打印层级3 25 if type(nesting) ~= "number" then 26 nesting = 3 27 end 28 29 local lookupTable = {} 30 local result = {} 31 32 local function _v(v) 33 if type(v) == "string" then 34 v = "\"" .. v .. "\"" 35 end 36 return tostring(v) 37 end 38 39 local function _dump(value, description, indent, nest, keylen) 40 description = description or "<var>" 41 spc = "" 42 if type(keylen) == "number" then 43 spc = string.rep(" ",keylen - string.len(_v(description))) 44 end 45 46 if type(value) ~= "table" then 47 result[#result + 1] = string.format("%s%s%s = %s", indent, _v(description), spc, _v(value)) 48 elseif lookupTable[value] then 49 result[#result + 1] = string.format("%s%s%s = *REF*", indent, description, spc) 50 else 51 lookupTable[value] = true 52 if nest > nesting then 53 result[#result + 1] = string.format("%s%s = *MAX NESTING*", indent, description) 54 else 55 result[#result + 1] = string.format("%s%s = {" , indent, _v(description)) 56 local indent2 = indent .. " " 57 local keys = {} 58 local keylen = 0 59 local values = {} 60 for k, v in pairs(value) do 61 keys[#keys + 1] = k 62 local vk = _v(k) 63 local vk1 = string.len(vk) 64 if vk1 > keylen then 65 keylen = vk1 66 end 67 values[k] = v 68 end 69 table.sort(keys,function(a, b) 70 if type(a) == "number" and type(b) == "number" then 71 return a < b 72 else 73 return tostring(a) < tostring(b) 74 end 75 end) 76 77 for i, k in pairs(keys) do 78 _dump(values[k], k, indent2,nest + 1,keylen) 79 end 80 result[#result + 1] = string.format("%s}", indent) 81 end 82 end 83 end 84 _dump(value,description, "- ", 1) 85 86 for i, line in pairs(result) do 87 print(line) 88 end 89 90 end