init.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. -- serialize_lib
  2. --[[
  3. Copyright (C) 2020 Moritz Blei (orwell96) and contributors
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Affero General Public License as
  6. published by the Free Software Foundation, either version 3 of the
  7. License, or (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Affero General Public License for more details.
  12. ]]--
  13. serialize_lib = {}
  14. --[[ Configuration table
  15. Whenever asked for a "config", the following table structure is expected:
  16. config = {
  17. skip_empty_tables = false -- if true, does not store empty tables
  18. -- On next read, keys that mapped to empty tables resolve to nil
  19. -- Used by: write_table_to_file
  20. }
  21. Not all functions use all of the parameters, so you can simplify your config sometimes
  22. ]]
  23. -- log utils
  24. -- =========
  25. function serialize_lib.log_error(text)
  26. minetest.log("error", "[serialize_lib] ("..(minetest.get_current_modname() or "?").."): "..(text or "<nil>"))
  27. end
  28. function serialize_lib.log_warn(text)
  29. minetest.log("warning", "[serialize_lib] ("..(minetest.get_current_modname() or "?").."): "..(text or "<nil>"))
  30. end
  31. function serialize_lib.log_info(text)
  32. minetest.log("action", "[serialize_lib] ("..(minetest.get_current_modname() or "?").."): "..(text or "<nil>"))
  33. end
  34. function serialize_lib.log_debug(text)
  35. minetest.log("action", "[serialize_lib] ("..(minetest.get_current_modname() or "?")..") DEBUG: "..(text or "<nil>"))
  36. end
  37. -- basic serialization/deserialization
  38. -- ===================================
  39. local mp = minetest.get_modpath(minetest.get_current_modname())
  40. serialize_lib.serialize = dofile(mp.."/serialize.lua")
  41. dofile(mp.."/atomic.lua")
  42. local ser = serialize_lib.serialize
  43. -- Opens the passed filename, and returns deserialized table
  44. -- When an error occurs, logs an error and returns false
  45. function serialize_lib.read_table_from_file(filename)
  46. local succ, ret = pcall(ser.read_from_file, filename)
  47. if not succ then
  48. serialize_lib.log_error(ret)
  49. return false,ret
  50. end
  51. return ret
  52. end
  53. -- Writes table into file
  54. -- When an error occurs, logs an error and returns false
  55. function serialize_lib.write_table_to_file(root_table, filename)
  56. local succ, ret = pcall(ser.write_to_file, root_table, filename)
  57. if not succ then
  58. serialize_lib.log_error(ret)
  59. return false,ret
  60. end
  61. return true
  62. end