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

[Lua] Saving variable names and values to a file

Started by civilwargeeky, 19 May 2013 - 08:00 PM
civilwargeeky #1
Posted 19 May 2013 - 10:00 PM
So I have a quarry program, and I am working on persistence. I have most of working, but I can't get the values of variables into the file. The current way I have it set up is I have an array of all the different variables I want to transfer (as strings), and then I'm using a loadstring to return the value of the "string" which is the name of a variable (all variables are local to the program). Here is about how it is set up now.

--Way at the top
local x , y, z = 0,0,0
--Assignment of vars
--About halfway down code
local restoreVars = {"x","y","z","pretendThereAreMoreThings"}
function saveProgress()
  file = fs.open("fileName", "w")
  for i=1, #restoreVars do
	file.write(restoreVars[i].." = "..tostring(setfenv(loadstring("return "..restoreVars[i]),getfenv())()).."\n")
  end
  file.close()
end
--Later
local function mine()
  --Do mining stuff
  saveProgress()
end 
Now, the writing part works, but the part with loadstring does not. The output file gets
x = nil
y = nil
z = nil
everythingElse = nil 

Also, just to break down the complicated part involving loadstring, it setting the environment of the function returned by loadstring to the program's local global environment (so it can see variables theoretically). Then it calls that function to return the value of the variable in the program, and tostrings it.

What am I doing wrong?
lieudusty #2
Posted 19 May 2013 - 10:10 PM
You are saving the string "x" to a file?

local restoreVars = {"x","y","z","pretendThereAreMoreThings"}

Try removing the quotes in the table: local restoreVars = {x,y,z,"pretendThereAreMoreThings"}


Nevermind I'm stupid and didn't read everything
civilwargeeky #3
Posted 19 May 2013 - 10:14 PM
You are saving the string "x" to a file?

local restoreVars = {"x","y","z","pretendThereAreMoreThings"}

Try removing the quotes in the table: local restoreVars = {x,y,z,"pretendThereAreMoreThings"}
No, the loadstring is giving the value of "return x", which is 0 (at the moment). What I want is " x = 0 " to appear in the file. If I wanted to I could make a table with ["x"] = x and iterate with "for a, b in pairs(restoreVars) do", but this should work!
Grim Reaper #4
Posted 19 May 2013 - 10:50 PM
You could serialize the variables using the textutils API and simply unserialize them when you're reading them back from the file.

Writing:

local restoreVariables = {x = 0, y = 0, z = 0}
local filePath   = "vars"
local fileHandle = fs.open (filePath, 'w')
fileHandle.write (textutils.serialize (restoreVariables))
fileHandle.close()

Reading:

local restoreVariables = nil
local filePath   = "vars"
local fileHandle = fs.open (filePath, 'r')
restoreVariables = textutils.unserialize (fileHandle.readAll())
fileHandle.close()