misc_helpers.lua 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. -- Minetest: builtin/misc_helpers.lua
  2. function basic_dump2(o)
  3. if type(o) == "number" then
  4. return tostring(o)
  5. elseif type(o) == "string" then
  6. return string.format("%q", o)
  7. elseif type(o) == "boolean" then
  8. return tostring(o)
  9. elseif type(o) == "function" then
  10. return "<function>"
  11. elseif type(o) == "userdata" then
  12. return "<userdata>"
  13. elseif type(o) == "nil" then
  14. return "nil"
  15. else
  16. error("cannot dump a " .. type(o))
  17. return nil
  18. end
  19. end
  20. function dump2(o, name, dumped)
  21. name = name or "_"
  22. dumped = dumped or {}
  23. io.write(name, " = ")
  24. if type(o) == "number" or type(o) == "string" or type(o) == "boolean"
  25. or type(o) == "function" or type(o) == "nil"
  26. or type(o) == "userdata" then
  27. io.write(basic_dump2(o), "\n")
  28. elseif type(o) == "table" then
  29. if dumped[o] then
  30. io.write(dumped[o], "\n")
  31. else
  32. dumped[o] = name
  33. io.write("{}\n") -- new table
  34. for k,v in pairs(o) do
  35. local fieldname = string.format("%s[%s]", name, basic_dump2(k))
  36. dump2(v, fieldname, dumped)
  37. end
  38. end
  39. else
  40. error("cannot dump a " .. type(o))
  41. return nil
  42. end
  43. end
  44. function dump(o, dumped)
  45. dumped = dumped or {}
  46. if type(o) == "number" then
  47. return tostring(o)
  48. elseif type(o) == "string" then
  49. return string.format("%q", o)
  50. elseif type(o) == "table" then
  51. if dumped[o] then
  52. return "<circular reference>"
  53. end
  54. dumped[o] = true
  55. local t = {}
  56. for k,v in pairs(o) do
  57. t[#t+1] = "" .. k .. " = " .. dump(v, dumped)
  58. end
  59. return "{" .. table.concat(t, ", ") .. "}"
  60. elseif type(o) == "boolean" then
  61. return tostring(o)
  62. elseif type(o) == "function" then
  63. return "<function>"
  64. elseif type(o) == "userdata" then
  65. return "<userdata>"
  66. elseif type(o) == "nil" then
  67. return "nil"
  68. else
  69. error("cannot dump a " .. type(o))
  70. return nil
  71. end
  72. end
  73. function string:split(sep)
  74. local sep, fields = sep or ",", {}
  75. local pattern = string.format("([^%s]+)", sep)
  76. self:gsub(pattern, function(c) fields[#fields+1] = c end)
  77. return fields
  78. end
  79. function string:trim()
  80. return (self:gsub("^%s*(.-)%s*$", "%1"))
  81. end
  82. assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
  83. function minetest.pos_to_string(pos)
  84. return "(" .. pos.x .. "," .. pos.y .. "," .. pos.z .. ")"
  85. end