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

How do you save a table or string for after you shutdown or terminate a program?

Started by MostwantedRBX, 08 March 2014 - 03:40 AM
MostwantedRBX #1
Posted 08 March 2014 - 04:40 AM
Hello, guys! I wanted to see if you guys know how to save data in a program, such as strings, tables, integers, etc. :D/>

I would like to save a table(or string, I can make a function to decipher one, if need be) that holds the settings for my operating system:

Settings = {
  Dropshadow = {true},
  Theme = {"Default"},
  TheCake = {"Is a Lie"} --Dummy space, for now.
}

I've seen this done in quite a few operating systems and I'm not new to Lua at all, I just never learned how to do this part. I'd appreciate any advice in this situation a lot! Explanations are also welcome, so I can understand why stuff is. Getting better is always a good thing. :P/>
Lyqyd #2
Posted 08 March 2014 - 04:57 AM
You'd usually write your data to a settings file, using the fs API. If you want an easy way to store a table, you can use the textutils API's serialization and unserialization functions along with the fs or io API.
MostwantedRBX #3
Posted 08 March 2014 - 05:34 AM
Ah, ok. :D/> Thanks for the help, I figured out how to load strings and stuff, still working on tables!

Alrighty, I did it! :D/> I made a loading and saving function for strings, numbers and tables. lol. Code:


MyTable = {
Chocolate = "No",
Lettuce = true,
Tomatoes = "Yes",
Cheese = true,
Beef = true,
Taco_Shell = true
}
local function Save(File, Data, IsTable)
  local File = fs.open(File,"w")
  if IsTable then
File.write(textutils.serialize(Data))
File.close()
  else
	File.write(Data)
File.close()
  end
end
local function Load(File, IsTable)
  local File = fs.open(File,"r")
  local Data = File.readAll()
  File.close()
  if IsTable then
return textutils.unserialize(Data)
  else
return Data
  end
end
Save("TestTable", MyTable, true)
UnserializedTable = Load("TestTable", true)
print("Do you want chocolate on your taco? "..UnserializedTable.Chocolate)

Thanks for your direction pointing, Lyqyd.