_hx_tostring.lua 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. function _hx_print_class(obj, depth)
  2. local first = true
  3. local result = ''
  4. for k,v in pairs(obj) do
  5. if first then
  6. result = result .. ','
  7. first = false
  8. end
  9. if _hx_hidden[k] == nil then
  10. result = result .. k .. ':' .. _hx_tostring(v, depth+1)
  11. end
  12. end
  13. return result
  14. end
  15. function _hx_print_enum(o, depth)
  16. if o.length == 2 then
  17. return o[0]
  18. else
  19. local str = o[0] .. "("
  20. for i = 2, (o.length-1) do
  21. if i ~= 2 then
  22. str = str .. "," .. _hx_tostring(o[i], depth+1)
  23. else
  24. str = str .. _hx_tostring(o[i], depth+1)
  25. end
  26. end
  27. return str .. ")"
  28. end
  29. end
  30. function _hx_tostring(obj, depth)
  31. if depth == nil then
  32. depth = 0
  33. elseif depth > 5 then
  34. return "<...>"
  35. end
  36. local tstr = _G.type(obj)
  37. if tstr == "string" then return obj
  38. elseif tstr == "nil" then return "null"
  39. elseif tstr == "number" then
  40. if obj == _G.math.POSITIVE_INFINITY then return "Infinity"
  41. elseif obj == _G.math.NEGATIVE_INFINITY then return "-Infinity"
  42. elseif obj == 0 then return "0"
  43. elseif obj ~= obj then return "NaN"
  44. else return _G.tostring(obj)
  45. end
  46. elseif tstr == "boolean" then return _G.tostring(obj)
  47. elseif tstr == "userdata" then
  48. local mt = _G.getmetatable(obj)
  49. if mt ~= nil and mt.__tostring ~= nil then
  50. return _G.tostring(obj)
  51. else
  52. return "<userdata>"
  53. end
  54. elseif tstr == "function" then return "<function>"
  55. elseif tstr == "thread" then return "<thread>"
  56. elseif tstr == "table" then
  57. if obj.__enum__ ~= nil then
  58. return _hx_print_enum(obj, depth)
  59. elseif obj.toString ~= nil and not _hx_is_array(obj) then return obj:toString()
  60. elseif _hx_is_array(obj) then
  61. if obj.length > 5 then
  62. return "[...]"
  63. else
  64. str = ""
  65. for i=0, (obj.length-1) do
  66. if i == 0 then
  67. str = str .. _hx_tostring(obj[i], depth+1)
  68. else
  69. str = str .. "," .. _hx_tostring(obj[i], depth+1)
  70. end
  71. end
  72. return "[" .. str .. "]"
  73. end
  74. elseif obj.__class__ ~= nil then
  75. return _hx_print_class(obj, depth)
  76. else
  77. first = true
  78. buffer = {}
  79. for k,v in pairs(obj) do
  80. if _hx_hidden[k] == nil then
  81. _G.table.insert(buffer, _hx_tostring(k, depth+1) .. ' : ' .. _hx_tostring(obj[k], depth+1))
  82. end
  83. end
  84. return "{ " .. table.concat(buffer, ", ") .. " }"
  85. end
  86. else
  87. _G.error("Unknown Lua type", 0)
  88. return ""
  89. end
  90. end