This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
tompy97's profile picture

Help with persistence API

Started by tompy97, 16 May 2013 - 05:53 AM
tompy97 #1
Posted 16 May 2013 - 07:53 AM
Hi, I'm using this persistence API in my turtle programs: http://pastebin.com/i9XBtvS2

The API is working perfectly, but it throws an error if I try and call a variable that hasn't been stored yet. I would like to know how I would change the API so that instead of throwing an error, it could return a string or a 0 or a nil or something else appropriate. Thank you for your help!
SadKingBilly #2
Posted 16 May 2013 - 07:59 AM
It throws an error because it tries to read from a file that doesn't exist. This will return nil if the file does not exist:

function pull(sName)
   local filePath = fs.combine("/.persistence", sName)
   if fs.exists(filePath) then
	 local handle = fs.open(filePath, "r")
	 local stuff = handle.readAll()
	 handle.close()
	 return textutils.unserialize(stuff)
   else
	 return nil
   end
end