Advertisement
osmarks

PotatoRegistry

Jan 25th, 2019
2,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.63 KB | None | 0 0
  1. local ser = ((require or dofile) "ser")
  2.  
  3. function split(self, separator, max)
  4.     local out = {}
  5.     if self:len() > 0 then
  6.         max = max or -1
  7.  
  8.         local field, start = 1, 1
  9.         local first, last = self:find(separator, start, true)
  10.         while first and max ~= 0 do
  11.             out[field] = self:sub(start, first - 1)
  12.             field = field + 1
  13.             start = last + 1
  14.             first , last = self:find(separator, start, true)
  15.             max = max - 1
  16.         end
  17.         out[field] = self:sub(start)
  18.    end
  19.  
  20.    return out
  21. end
  22.  
  23. local function fwrite(n, c)
  24.     local f = fs.open(n, "wb")
  25.     f.write(c)
  26.     f.close()
  27. end
  28.  
  29. local function fread(n)
  30.     local f = fs.open(n, "rb")
  31.     local out = f.readAll()
  32.     f.close()
  33.     return out
  34. end
  35.  
  36. local fsopen = fs.open
  37. local registry_path = ".registry"
  38. local registry = {}
  39.  
  40. function registry.set(key, value)
  41.     local path = split(key, ".")
  42.     local ok, orig_data
  43.     if fs.exists(registry_path) then
  44.         ok, orig_data = pcall(ser.deserialize, fread(registry_path))
  45.         if not ok then orig_data = {} end
  46.     else
  47.         orig_data = {}
  48.     end
  49.     local last_bit = table.remove(path)
  50.     local data = orig_data
  51.     for _, seg in ipairs(path) do
  52.         local new_bit = data[seg]
  53.         if type(new_bit) ~= "table" then data[seg] = {} end
  54.         data = data[seg]
  55.     end
  56.     data[last_bit] = value
  57.     fwrite(registry_path, ser.serialize(orig_data))
  58. end
  59.  
  60. function registry.get(key)
  61.     if not fs.exists(registry_path) then return nil end
  62.     local path = split(key, ".")
  63.     local ok, data = pcall(ser.deserialize, fread(registry_path))
  64.     if not ok then data = {} end
  65.     for _, seg in ipairs(path) do
  66.         data = data[seg]
  67.         if not data then return nil end
  68.     end
  69.     return data
  70. end
  71.  
  72. return registry
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement