kovakovi2000

ldb3

Oct 31st, 2025 (edited)
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.12 KB | None | 0 0
  1. -- ldb3
  2. -- tiny file DB stored in /data/<db>/<key>
  3.  
  4. local ROOT = "/data"
  5.  
  6. if not fs.exists(ROOT) then
  7.   fs.makeDir(ROOT)
  8. end
  9.  
  10. local function dbPath(db)
  11.   return ROOT .. "/" .. db
  12. end
  13.  
  14. local function recPath(db, key)
  15.   return dbPath(db) .. "/" .. key
  16. end
  17.  
  18. local function ensure(db)
  19.   local p = dbPath(db)
  20.   if not fs.exists(p) then
  21.     fs.makeDir(p)
  22.   end
  23. end
  24.  
  25. function set(db, key, value)
  26.   ensure(db)
  27.   local h = fs.open(recPath(db, key), "w")
  28.   h.write(textutils.serialize(value))
  29.   h.close()
  30. end
  31.  
  32. function get(db, key, default)
  33.   local p = recPath(db, key)
  34.   if not fs.exists(p) then
  35.     return default
  36.   end
  37.   local h = fs.open(p, "r")
  38.   local raw = h.readAll()
  39.   h.close()
  40.   local ok, val = pcall(textutils.unserialize, raw)
  41.   if ok then
  42.     return val
  43.   else
  44.     return default
  45.   end
  46. end
  47.  
  48. function list(db)
  49.   local p = dbPath(db)
  50.   if not fs.exists(p) then return {} end
  51.   return fs.list(p)
  52. end
  53.  
  54. function del(db, key)
  55.   local p = recPath(db, key)
  56.   if fs.exists(p) then fs.delete(p) end
  57. end
  58.  
  59. function clear(db)
  60.   for _, name in ipairs(list(db)) do
  61.     del(db, name)
  62.   end
  63. end
Advertisement
Add Comment
Please, Sign In to add comment