树形打印table

    1. function table.print (val)
    2. local function loop (val, keyType, _indent)
    3. _indent = _indent or 1
    4. keyType = keyType or "string"
    5. local res = ""
    6. local indentStr = " " -- 缩进空格
    7. local indent = string.rep(indentStr, _indent)
    8. local end_indent = string.rep(indentStr, _indent - 1)
    9. local putline = function (...)
    10. local arr = { res, ... }
    11. for i = 1, #arr do
    12. if type(arr[i]) ~= "string" then arr[i] = tostring(arr[i]) end
    13. end
    14. res = table.concat(arr)
    15. end
    16. if type(val) == "table" then
    17. putline("{ ")
    18. if #val > 0 then
    19. local index = 0
    20. local block = false
    21. for i = 1, #val do
    22. local n = val[i]
    23. if type(n) == "table" or type(n) == "function" then
    24. block = true
    25. break
    26. end
    27. end
    28. if block then
    29. for i = 1, #val do
    30. local n = val[i]
    31. index = index + 1
    32. if index == 1 then putline("\n") end
    33. putline(indent, loop(n, type(i), _indent + 1), "\n")
    34. if index == #val then putline(end_indent) end
    35. end
    36. else
    37. for i = 1, #val do
    38. local n = val[i]
    39. index = index + 1
    40. putline(loop(n, type(i), _indent + 1))
    41. end
    42. end
    43. else
    44. putline("\n")
    45. for k, v in pairs(val) do
    46. putline(indent, k, " = ", loop(v, type(k), _indent + 1), "\n")
    47. end
    48. putline(end_indent)
    49. end
    50. putline("}, ")
    51. elseif type(val) == "string" then
    52. val = string.gsub(val, "\a", "\\a") -- 响铃(BEL)
    53. val = string.gsub(val, "\b", "\\b") -- 退格(BS),将当前位置移到前一列
    54. val = string.gsub(val, "\f", "\\f") -- 换页(FF),将当前位置移到下页开头
    55. val = string.gsub(val, "\n", "\\n") -- 换行(LF),将当前位置移到下一行开头
    56. val = string.gsub(val, "\r", "\\r") -- 回车(CR),将当前位置移到本行开头
    57. val = string.gsub(val, "\t", "\\t") -- 水平指标(HT),(调用下一个TAB位置)
    58. val = string.gsub(val, "\v", "\\v") -- 垂直指标(VT)
    59. putline("\"", val, "\", ")
    60. elseif type(val) == "boolean" then
    61. putline(val and "true, " or "false, ")
    62. elseif type(val) == "function" then
    63. putline(tostring(val), ", ")
    64. elseif type(val) == "nil" then
    65. putline("nil, ")
    66. else
    67. putline(val, ", ")
    68. end
    69. return res
    70. end
    71. local res = loop(val)
    72. res = string.gsub(res, ",(%s*})", "%1")
    73. res = string.gsub(res, ",(%s*)$", "%1")
    74. res = string.gsub(res, "{%s+}", "{}")
    75. return res
    76. end