init.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. datastorage = {data = {}}
  2. local DIR_DELIM = DIR_DELIM or "/"
  3. local data_path = minetest.get_worldpath()..DIR_DELIM.."datastorage"..DIR_DELIM
  4. function datastorage.save(id)
  5. local data = datastorage.data[id]
  6. -- Check if the container is empty
  7. if not data or not next(data) then return end
  8. for _, sub_data in pairs(data) do
  9. if not next(sub_data) then return end
  10. end
  11. local file = io.open(data_path..id, "w")
  12. if not file then
  13. -- Most likely the data directory doesn't exist, create it
  14. -- and try again.
  15. if minetest.mkdir then
  16. minetest.mkdir(data_path)
  17. else
  18. -- Using os.execute like this is not very platform
  19. -- independent or safe, but most platforms name their
  20. -- directory creation utility mkdir, the data path is
  21. -- unlikely to contain special characters, and the
  22. -- data path is only mutable by the admin.
  23. os.execute('mkdir "'..data_path..'"')
  24. end
  25. file = io.open(data_path..id, "w")
  26. if not file then return end
  27. end
  28. local datastr = minetest.serialize(data)
  29. if not datastr then return end
  30. file:write(datastr)
  31. file:close()
  32. return true
  33. end
  34. function datastorage.load(id)
  35. local file = io.open(data_path..id, "r")
  36. if not file then return end
  37. local data = minetest.deserialize(file:read("*all"))
  38. datastorage.data[id] = data
  39. file:close()
  40. return data
  41. end
  42. -- Compatability
  43. function datastorage.get_container(player, id)
  44. return datastorage.get(player:get_player_name(), id)
  45. end
  46. -- Retrieves a value from the data storage
  47. function datastorage.get(id, ...)
  48. local last = datastorage.data[id]
  49. if last == nil then last = datastorage.load(id) end
  50. if last == nil then
  51. last = {}
  52. datastorage.data[id] = last
  53. end
  54. local cur = last
  55. for _, sub_id in ipairs({...}) do
  56. last = cur
  57. cur = cur[sub_id]
  58. if cur == nil then
  59. cur = {}
  60. last[sub_id] = cur
  61. end
  62. end
  63. return cur
  64. end
  65. -- Saves a container and reomves it from memory
  66. function datastorage.finish(id)
  67. datastorage.save(id)
  68. datastorage.data[id] = nil
  69. end
  70. -- Compatability
  71. function datastorage.save_container(player)
  72. return datastorage.save(player:get_player_name())
  73. end
  74. minetest.register_on_leaveplayer(function(player)
  75. local player_name = player:get_player_name()
  76. datastorage.save(player_name)
  77. datastorage.data[player_name] = nil
  78. end)
  79. minetest.register_on_shutdown(function()
  80. for id in pairs(datastorage.data) do
  81. datastorage.save(id)
  82. end
  83. end)