nSun

CC API cookie

Apr 4th, 2014
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.60 KB | None | 0 0
  1. local cookieDir = "/cookies"
  2. local boot = false
  3.  
  4. -- Initialise le répertoire de stockage
  5. -- @return bool
  6. local function _reboot()
  7.     if not boot then
  8.         if not fs.isDir(cookieDir) then
  9.             fs.makeDir(cookieDir)
  10.             boot = fs.isDir(cookieDir)
  11.         end
  12.     end
  13.     return boot
  14. end
  15.  
  16. -- Retourne les données du fichier
  17. -- @param   string  label   Nom du fichier
  18. -- @return  table   data
  19. function get(label)
  20.     if not _reboot() then
  21.         print("cookie.get() : Couldn't load "..cookieDir)
  22.         return nil
  23.     end
  24.    
  25.     local data = { }
  26.     local path = cookieDir.."/"..label
  27.     -- check file data
  28.     if fs.exists(path) then
  29.         local handle = assert(fs.open(path, "r"), "fs.open() : Couldn't load "..path) -- this file is opened in read mode
  30.         local input = handle.readAll() -- input is now the serialized table
  31.         handle.close()
  32.     -- -- load data
  33.         data = textutils.unserialize(input) -- this will decode our table
  34.         return data
  35.     else
  36.         print("cookie.get() : Couldn't load "..path)
  37.         return nil
  38.     end
  39. end
  40.  
  41. -- Consigne les données dans un fichier
  42. -- @param   string  label   Nom du fichier
  43. -- @param   table   data    Tableau des variables à stocker
  44. -- @return  bool    success
  45. function set(label, data)
  46.     if not _reboot() then
  47.         print("cookie.set() : Couldn't load "..cookieDir)
  48.         return false
  49.     end
  50.    
  51.     local path = cookieDir.."/"..label
  52.     local output = textutils.serialize(data)
  53.     local handle = assert(fs.open(path, "w"), "fs.open() : Couldn't save "..path) -- this will give you an error if something's gone wrong
  54.     handle.write(output) -- this is where the magic happens, we're storing the entire "target" table
  55.     handle.close()
  56.     return true
  57. end
Advertisement
Add Comment
Please, Sign In to add comment