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

Variables to multiple files or just to one file

Started by The Inspector, 14 March 2013 - 10:44 PM
The Inspector #1
Posted 14 March 2013 - 11:44 PM
Pretty much I have 9 different variables which all need to be saved to file constantly (to avoid chunk unloading, disconnecting etc) These variables all change at different times and every time they change is when they have to be saved to file. Now which is the better method to do with:

1 File with all the variables on different lines, so that every time it saves, it has to write each variable on a new line (overriding previous values)

1 File per variable, so that every time it saves its only editing one line in one file. In end there would be 9 different files all only containing 1 value.

The variables are only ever loaded on start up.
theoriginalbit #2
Posted 14 March 2013 - 11:51 PM
really it is personal choice. there are a few programs out there designed to do similar things to this. but personally i prefer one file on the system. so you would need to write all variables each time, since there is no seek on files in CC.
Kryptanyte #3
Posted 14 March 2013 - 11:58 PM
assuming you are writing these to a single file and insert the new variable into a main table try this for writing:


function writeVar(saveTable)

    save = textutils.serialize(saveTable)
    file = fs.open("variables", "w")
    file.write(save)
    file.close()
    
end

Then something like this for getting the variables from the file:


function getVar()

    file = fs.open("variables", "r")
    vars = file.readAll()
    file.close()
    returnVars = textutils.unserialize(vars)
    
    return returnVars

end

I hope you know how to use these, I am terrible at explaining code…
The Inspector #4
Posted 15 March 2013 - 12:04 AM
Yeah I understand it, I just wanted to make sure, that opening heaps of files at a time didn't cause problems, or that writing multiple variables at a time would slow down my code. If that method you posted Kryptanyte returns a table (which I assume it does) then I will probably use something similar to that as that was what I was kinda planning on.
theoriginalbit #5
Posted 15 March 2013 - 12:06 AM
technically writing to one file is faster than writing to multiple, but with only a few its very insignificant, its really only when there are LOTS of files.
Kryptanyte #6
Posted 15 March 2013 - 12:07 AM
If you are making your own code for it, before you save remember to use x = textutils.serialize(table) and save x then when you read from the file x = textutils.unserialize(table from file read) then use x as the variable table
The Inspector #7
Posted 15 March 2013 - 12:24 AM
Righto thanks.
LBPHacker #8
Posted 15 March 2013 - 04:48 AM
BTW You should have searched for a topic in Tutorials - you could've found this topic...