Advertisement
kreezxil

serialization for computercraft NF 1.21.1+

Sep 23rd, 2024
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.19 KB | Gaming | 0 0
  1. local serialization = {}
  2.  
  3. -- Function to serialize a table and write it to a file
  4. function serialization.saveTableToFile(tbl, fileName)
  5.     if type(tbl) ~= "table" then
  6.         error("The first argument must be a table", 2)
  7.     end
  8.    
  9.     local file = fs.open(fileName, "w")
  10.     if file then
  11.         local serializedData = textutils.serialize(tbl)
  12.         file.write(serializedData)
  13.         file.close()
  14.         return true
  15.     else
  16.         return false, "Failed to open file for writing."
  17.     end
  18. end
  19.  
  20. -- Function to read a file and deserialize its contents into a table
  21. function serialization.loadTableFromFile(fileName)
  22.     if not fs.exists(fileName) then
  23.         return false, "File does not exist."
  24.     end
  25.  
  26.     local file = fs.open(fileName, "r")
  27.     if file then
  28.         local serializedData = file.readAll()
  29.         file.close()
  30.         local deserializedTable = textutils.unserialize(serializedData)
  31.         if deserializedTable then
  32.             return deserializedTable
  33.         else
  34.             return false, "Failed to deserialize the file content."
  35.         end
  36.     else
  37.         return false, "Failed to open file for reading."
  38.     end
  39. end
  40.  
  41. return serialization
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement