Advertisement
osmarks

Simple Persistence

Feb 19th, 2019
1,865
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.86 KB | None | 0 0
  1. --[[
  2. Fixes PS#DE7E9F99
  3. Out-of-sandbox code/data files could be overwritten using this due to environment weirdness.
  4. Now persistence data is in its own folder so this will not happen.
  5. ]]
  6. local persist_dir = "persistence_data"
  7.  
  8. local function load_data(name)
  9.     local file = fs.combine(persist_dir, name)
  10.     if not fs.exists(file) then error "does not exist" end
  11.     local f = fs.open(file, "r")
  12.     local x = f.readAll()
  13.     f.close()
  14.     return textutils.unserialise(x)
  15. end
  16.  
  17. local function save_data(name, value)
  18.     if not fs.isDir(persist_dir) then fs.delete(persist_dir) fs.makeDir(persist_dir) end
  19.     local f = fs.open(fs.combine(persist_dir, name), "w")
  20.     f.write(textutils.serialise(value))
  21.     f.close()
  22. end
  23.  
  24. return function(name)
  25.     if type(name) ~= "string" then error "Name of persistence volume must be a string." end
  26.     local ok, data = pcall(load_data, name)
  27.     if not ok or not data then data = {} end
  28.     local mt = {}
  29.     setmetatable(data, mt)
  30.    
  31.     mt.__index = {
  32.         save = function()
  33.             save_data(name, data)
  34.         end,
  35.         reload = function()
  36.             -- swap table in place to keep references valid
  37.             for k in pairs(data) do data[k] = nil end
  38.             for k, v in pairs(load_data(name)) do
  39.                 data[k] = v
  40.             end
  41.         end
  42.     }
  43.  
  44.     function mt.__tostring(_)
  45.         return ("[PersistenceStore %s]"):format(name)
  46.     end
  47.  
  48.     return data
  49. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement