pp.lua 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. local function off(i)
  2. local ss = ''
  3. local j = 0
  4. while j < i do
  5. ss = ss .. ' '
  6. j = j + 1
  7. end
  8. return ss
  9. end
  10. local function fmtkey(key)
  11. if type(key) == 'string' and key:match('^[_%a][_%w]*$') then
  12. return key
  13. end
  14. return '[' .. string.format('%q', key) .. ']'
  15. end
  16. local function pp(v, i)
  17. if type(v) == "string" then
  18. return string.format('%q', v)
  19. end
  20. if type(v) == "number" then
  21. return tostring(v)
  22. end
  23. if type(v) == "nil" then
  24. return 'nil'
  25. end
  26. if type(v) == "boolean" then
  27. return tostring(v)
  28. end
  29. if type(v) == "table" then
  30. local ret = "{\n"
  31. local curoff = 1
  32. for x, y in pairs(v) do
  33. if type(x) == 'number' and x == curoff then
  34. ret = ret .. off(i + 1) .. pp(y, i + 1) .. ';\n'
  35. curoff = curoff + 1
  36. else
  37. ret = ret .. off(i + 1) .. fmtkey(x) .. " = " .. pp(y, i + 1) .. ';\n'
  38. end
  39. end
  40. return ret .. off(i) .. "}"
  41. end
  42. if v == nil then
  43. return 'nil'
  44. end
  45. return ""
  46. end
  47. local function prettify(v)
  48. return pp(v, 0)
  49. end