Advertisement
MolSno

Untitled

Jul 18th, 2025
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.05 KB | None | 0 0
  1. local function save(filename, data)
  2.   local handle, err = fs.open(filename, 'w') -- w for write
  3.   if handle then
  4.     handle.write(textutils.serialize(data)) -- write the data, serialized.
  5.     handle.close() -- closing the handle is what actually saves.
  6.     -- very important to close filehandles.
  7.   else
  8.     -- Throw an error pointing to the calling function.
  9.     error("Failed to save data: " .. tostring(err), 2)
  10.   end
  11. end
  12.  
  13. local function load(filename, default_value)
  14.   local handle = fs.open(filename, 'r') -- r for read
  15.   if handle then
  16.     local data = handle.readAll()
  17.     handle.close() -- again, important to close these.
  18.    
  19.     return textutils.unserialize(data) -- Unserialize the data and return it.
  20.   end
  21.  
  22.   -- If we got here, the file did not exist.
  23.   return default_value
  24. end
  25.  
  26. -- Usage
  27.  
  28. local data = {x = 32, y = 64}
  29.  
  30. save("position.txt", data)
  31.  
  32. local loaded_data = load("position.txt", {x = 0, y = 0})
  33. -- loaded_data will be {x = 32, y = 64}
  34. -- Unless you delete `position.txt`, in which case it will be {x = 0, y = 0}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement