stringify.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. local table_concat = table.concat
  2. local table_insert = table.insert
  3. local string_rep = string.rep
  4. -- return function(root)
  5. -- local cache = { [root] = "." }
  6. -- local function dump(t, space, name)
  7. -- local stack = {}
  8. -- for k, v in pairs(t) do
  9. -- local key = tostring(k)
  10. -- if cache[v] then
  11. -- table_insert(stack,"+" .. key .. " {" .. cache[v].."}")
  12. -- elseif type(v) == "table" then
  13. -- local new_key = name .. "." .. key
  14. -- local new_space = space .. (next(t,k) and "|" or " " ) .. string_rep(" ",#key)
  15. -- cache[v] = new_key
  16. -- table_insert(stack, "+" .. key .. dump(v, new_space, new_key))
  17. -- else
  18. -- table_insert(stack,"+" .. key .. " [" .. tostring(v).."]")
  19. -- end
  20. -- end
  21. -- return table_concat(stack, "\n"..space)
  22. -- end
  23. -- return dump(root, "", "")
  24. -- end
  25. function dump(tbl)
  26. assert(type(tbl) == "table")
  27. local str = ""
  28. local tbl_record = {}
  29. local function dump_table(t, space, toptable)
  30. str = str .. ("{\n")
  31. local keys = {}
  32. for k in pairs(t) do
  33. table.insert(keys, k)
  34. end
  35. -- table.sort(keys)
  36. tbl_record[t] = true
  37. for _,k in ipairs(keys) do
  38. local v = rawget(t, k)
  39. local tk = type(k)
  40. if tk == "number" then
  41. str = str .. space .. " [" .. k .. "] = "
  42. elseif tk == "string" then
  43. str = str .. space .. " " .. k .. " = "
  44. else
  45. str = str .. "[UNKNOWN: " .. tostring(k) .. "] = "
  46. end
  47. local tv = type(v)
  48. if tv == "number" then
  49. str = str .. v .. ",\n"
  50. elseif tv == "string" then
  51. if v:find('"') then
  52. str = str .. "[=[" .. v .. "]=],\n"
  53. else
  54. str = str .. '"' .. v .. '",\n'
  55. end
  56. elseif tv == "boolean" then
  57. str = str .. (v and "true" or "false") .. ",\n"
  58. elseif tv == "table" then
  59. if tbl_record[v] then
  60. str = str .. "[RECURSIVE TABLE],\n"
  61. else
  62. dump_table(v, space .. " ")
  63. end
  64. else
  65. str = str .. "[UNKNOWN: " .. tostring(v) .. "],\n"
  66. end
  67. end
  68. str = str .. space .. "}" .. (toptable and "" or ",") .. "\n"
  69. end
  70. dump_table(tbl, "", true)
  71. return str
  72. end
  73. return dump