_hx_tostring.lua 2.9 KB

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