,转lua dump函数

[cpp]view plaincopy

  1. function dump(value, desciption, nesting)
  2. if type(nesting) ~= "number" then nesting = 3 end
  3. local lookupTable = {}
  4. local result = {}
  5. local function _v(v)
  6. if type(v) == "string" then
  7. v = "\"" .. v .. "\""
  8. end
  9. return tostring(v)
  10. end
  11. local traceback = string.split(debug.traceback("", 2), "\n")
  12. print("dump from: " .. string.trim(traceback[3]))
  13. local function _dump(value, desciption, indent, nest, keylen)
  14. desciption = desciption or "<var>"
  15. spc = ""
  16. if type(keylen) == "number" then
  17. spc = string.rep(" ", keylen - string.len(_v(desciption)))
  18. end
  19. if type(value) ~= "table" then
  20. result[#result +1 ] = string.format("%s%s%s = %s", indent, _v(desciption), spc, _v(value))
  21. elseif lookupTable[value] then
  22. result[#result +1 ] = string.format("%s%s%s = *REF*", indent, desciption, spc)
  23. else
  24. lookupTable[value] = true
  25. if nest > nesting then
  26. result[#result +1 ] = string.format("%s%s = *MAX NESTING*", indent, desciption)
  27. else
  28. result[#result +1 ] = string.format("%s%s = {", indent, _v(desciption))
  29. local indent2 = indent.." "
  30. local keys = {}
  31. local keylen = 0
  32. local values = {}
  33. for k, v in pairs(value) do
  34. keys[#keys + 1] = k
  35. local vk = _v(k)
  36. local vkl = string.len(vk)
  37. if vkl > keylen then keylen = vkl end
  38. values[k] = v
  39. end
  40. table.sort(keys, function(a, b)
  41. if type(a) == "number" and type(b) == "number" then
  42. return a < b
  43. else
  44. return tostring(a) < tostring(b)
  45. end
  46. end)
  47. for i, k in ipairs(keys) do
  48. _dump(values[k], k, indent2, nest + 1, keylen)
  49. end
  50. result[#result +1] = string.format("%s}", indent)
  51. end
  52. end
  53. end
  54. _dump(value, desciption, "- ", 1)
  55. for i, line in ipairs(result) do
  56. print(line)
  57. end
  58. end

用法:dump(t) --t为打印的内容

原文地址:https://blog.csdn.net/u013517637/article/details/53977732