Advertisement
CitraDeus

Saving

Jul 11th, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. The technique you've suggested is having a program that gets run to reload the data, and when you save your data, you modify the program. I have never heard of that style ever being used.
  2.  
  3. Conventionally, people create a save format. So when they read the file, they know what to expect and how to parse the data in the file into all the needed variables.
  4.  
  5. The easiest way to do this in computercraft is with an API called textutils. textutils has a function called serialize which will take a table and recursively turn it into a string format to be unserialized later. Here's an example of saving to the file.
  6. local a = 1
  7. local b = {}
  8. b.c = 2
  9. b.d = 3
  10. local e = "Test"
  11.  
  12. local tableToSave = {a=a,b=b,e=e}
  13. local stringToSave = textutils.serialize(tableToSave)
  14.  
  15. local file = assert(fs.open("path/to/file", "w"), "Failed to open file for saving")
  16. file.write(stringToSave)
  17. file.close()
  18.  
  19. Now the file has text similar to
  20. {["a"]=1,["b"]={["c"]=2,["d"]=3},["e"]="Test"}
  21.  
  22. Quick note, assert is a nice function that errors and closes your program if something goes wrong. The proper call is assert(someValue, errorMessage). Assert returns someValue if someValue is not false or nil. If it is false or nil, the program errors out with errorMessage.
  23.  
  24. To read this data back into variables from the file, read the text back into your program and use textutils.unserialize to get the data table back.
  25. local file = assert(fs.open("path/to/file", "r"), "Failed to open file for reading")
  26. local textToRead = file.readAll()
  27. file.close()
  28.  
  29. local tData = textutils.unserialize(textToRead)
  30. a = tData.a
  31. b = tData.b
  32. e = tData.e
  33.  
  34. Now a, b, and e are exactly the same as they were in the program that wrote them to file.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement