在lua中,table是比较常用的数据形式,有时候为了打印出里面的内容,需要做一些特殊处理。
废话不多讲,直接粘代码:
1 print = release_print 2 3 -- 递归打印table 4 local tableDump = function (tab, nesting) 5 if type(nesting) ~= "number" then nesting = 3 end 6 local info = debug.getinfo(2)--获取当前脚本所在的目录 7 print(string.format("%s : %s",info.source, info.currentline)) 8 9 local function getStr(value, is_key)--拼合table 10 if is_key then 11 if type(value) == "string" then 12 return value 13 else 14 return string.format('[%s]', tostring(value)) 15 end 16 else 17 if type(value) == "string" then 18 return string.format('"%s"', value) 19 else 20 return tostring(value) 21 end 22 end 23 end 24 25 if type(tab) ~= "table" then--当解析到最后一层表的时候递归返回 26 print(getStr(tab)) 27 return 28 end 29 30 print(tostring(tab).." = {") 31 local line = "" 32 local space = " " 33 local printTab 34 printTab = function(t) 35 line = line..space 36 for k,v in pairs(t) do 37 if type(v) == "table" then 38 if string.len(line)/string.len(space) >= nesting then 39 print(line..getStr(k, true).." = MAX NESTING,") 40 else 41 print(line..getStr(k, true).." = {") 42 printTab(v) 43 end 44 else 45 print(line..getStr(k, true).." = "..getStr(v)..',') 46 end 47 end 48 line = string.sub(line,1, string.len(line)-string.len(space)) 49 if line == "" then 50 print(line.."}") 51 else 52 print(line.."},") 53 end 54 end 55 printTab(tab) 56 end 57 58 _dump = tableDump 59 60 -- 重新载入脚本 61 SYS_REQUIREAGAIN_FLAG = true 62 function requireAgain(file_name) 63 if SYS_REQUIREAGAIN_FLAG then 64 if package.loaded[file_name] then 65 package.loaded[file_name] = nil 66 end 67 end 68 return require(file_name) 69 end
使用的时候直接以方法的使用规则使用
_dump(my_table)