Advertisement
MattiasBuelens

Common store

Jun 8th, 2012
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.66 KB | None | 0 0
  1. --[[
  2.  
  3.     Common utilities
  4.     Persistent storage
  5.  
  6. --]]
  7.  
  8. common = common or {}
  9.  
  10. local Store = common.newClass({
  11.     ___path = nil,
  12.     ___data = nil,
  13.     ___defaults = nil
  14. })
  15. common.Store = Store
  16.  
  17. function common.newStore(path, defaults)
  18.     assert(type(path) == "string", "path must be a string")
  19.     return Store:new{
  20.         ___path = path,
  21.         ___data = {},
  22.         ___defaults = defaults or {}
  23.     }
  24. end
  25.  
  26. function common.loadStore(path, defaults)
  27.     local store = common.newStore(path, defaults)
  28.     store:load()
  29.     return store:getAll()
  30. end
  31.  
  32. function Store:get(key)
  33.     local result = self.___data[key]
  34.     if result == nil then
  35.         result = self.___defaults[key]
  36.     end
  37.     return result
  38. end
  39.  
  40. function Store:getAll()
  41.     local t = {}
  42.     for k,v in pairs(self.___defaults) do
  43.         t[k] = v
  44.     end
  45.     for k,v in pairs(self.___data) do
  46.         t[k] = v
  47.     end
  48.     return t
  49. end
  50.  
  51. function Store:set(key, value)
  52.     self.___data[key] = value
  53. end
  54.  
  55. function Store:serialize()
  56.     return textutils.serialize(self:getAll())
  57. end
  58.  
  59. function Store:unserialize(data)
  60.     self.___data = textutils.unserialize(data)
  61. end
  62.  
  63. function Store:load()
  64.     if not fs.exists(self.___path) then
  65.         return false
  66.     end
  67.  
  68.     -- Load from file
  69.     local file = fs.open(self.___path, "r")
  70.     if file == nil then
  71.         return false
  72.     end
  73.  
  74.     self:unserialize(file.readAll())
  75.     file.close()
  76.     return true
  77. end
  78.  
  79. function Store:save()
  80.     -- Make directory
  81.     local dir = "/"..shell.resolve("/"..self.___path.."/..")
  82.     if not (fs.exists(dir) and fs.isDir(dir)) then
  83.         fs.makeDir(dir)
  84.     end
  85.  
  86.     -- Write to file
  87.     local file = fs.open(self.___path, "w")
  88.     if file == nil then
  89.         return false
  90.     end
  91.  
  92.     file.write(self:serialize())
  93.     file.close()
  94.     return true
  95. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement