2
0

init.lua 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. sethome = {}
  2. local homes_file = minetest.get_worldpath() .. "/homes"
  3. local homepos = {}
  4. local function loadhomes()
  5. local input = io.open(homes_file, "r")
  6. if not input then
  7. return -- no longer an error
  8. end
  9. -- Iterate over all stored positions in the format "x y z player" for each line
  10. for pos, name in input:read("*a"):gmatch("(%S+ %S+ %S+)%s([%w_-]+)[\r\n]") do
  11. homepos[name] = minetest.string_to_pos(pos)
  12. end
  13. input:close()
  14. end
  15. loadhomes()
  16. sethome.set = function(name, pos)
  17. local player = minetest.get_player_by_name(name)
  18. if not player or not pos then
  19. return false
  20. end
  21. player:set_attribute("sethome:home", minetest.pos_to_string(pos))
  22. -- remove `name` from the old storage file
  23. local data = {}
  24. local output = io.open(homes_file, "w")
  25. if output then
  26. homepos[name] = nil
  27. for i, v in pairs(homepos) do
  28. table.insert(data, string.format("%.1f %.1f %.1f %s\n", v.x, v.y, v.z, i))
  29. end
  30. output:write(table.concat(data))
  31. io.close(output)
  32. return true
  33. end
  34. return true -- if the file doesn't exist - don't return an error.
  35. end
  36. sethome.get = function(name)
  37. local player = minetest.get_player_by_name(name)
  38. local pos = minetest.string_to_pos(player:get_attribute("sethome:home"))
  39. if pos then
  40. return pos
  41. end
  42. -- fetch old entry from storage table
  43. pos = homepos[name]
  44. if pos then
  45. return vector.new(pos)
  46. else
  47. return nil
  48. end
  49. end
  50. sethome.go = function(name)
  51. local pos = sethome.get(name)
  52. local player = minetest.get_player_by_name(name)
  53. if player and pos then
  54. player:set_pos(pos)
  55. return true
  56. end
  57. return false
  58. end
  59. minetest.register_privilege("home", {
  60. description = "Can use /sethome and /home",
  61. give_to_singleplayer = false
  62. })
  63. minetest.register_chatcommand("home", {
  64. description = "Teleport you to your home point",
  65. privs = {home = true},
  66. func = function(name)
  67. if sethome.go(name) then
  68. return true, "Teleported to home!"
  69. end
  70. return false, "Set a home using /sethome"
  71. end,
  72. })
  73. minetest.register_chatcommand("sethome", {
  74. description = "Set your home point",
  75. privs = {home = true},
  76. func = function(name)
  77. name = name or "" -- fallback to blank name if nil
  78. local player = minetest.get_player_by_name(name)
  79. if player and sethome.set(name, player:get_pos()) then
  80. return true, "Home set!"
  81. end
  82. return false, "Player not found!"
  83. end,
  84. })