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

Write and Load a file?

Started by Tjakka5, 04 April 2013 - 07:01 PM
Tjakka5 #1
Posted 04 April 2013 - 09:01 PM
Hello,

I am trying to make some variables save-able and load-able from a file, but Im not sure how?
Left #2
Posted 04 April 2013 - 09:09 PM
os.loadAPI(fileLocation)

then filename.variable

Does that help?
Left #3
Posted 04 April 2013 - 09:11 PM
File 1 named config (Variable File)


someVar = "Some String"
-- DO NOT USE local. It needs to be GLOBAL

File 2 named startup (Reading File)


os.load("config")
print(config.someVar) -- Prints "Some String"
Engineer #4
Posted 04 April 2013 - 09:18 PM
os.loadAPI(fileLocation)

then filename.variable

Does that help?
File 1 named config (Variable File)


someVar = "Some String"
-- DO NOT USE local. It needs to be GLOBAL

File 2 named startup (Reading File)


os.load("config")
print(config.someVar) -- Prints "Some String"
For that your variables must be global, like you've said.

I suggest doing this:

-- Writing to a file
local handle = fs.open("path/to/file", "w")
handle.write(textutils.serialize(varName)
handle.close()
 
-- Reading
local handle = fs.open("path/to/file", "r")
local reader = handle.readAll()
handle.close()
local var = textutils.unserialize(reader)


:)/>
LBPHacker #5
Posted 05 April 2013 - 02:48 AM
-snip-

Yeah, serializing a table (yes, what Engineer's said actually does just that) and saving it is a bit more efficient than loading an API. APIs sometimes have fields, like CHANNEL_BROADCAST in rednet (1.4 or above), but that's not the point of an API - I mean, a bunch of variables is not exactly an Advanced Programming Interface, is it? (Okay, colors API maybe, but that's still not a config file).

What I want to say is that loading a config file by executing it is just not the sensible way to do it.


About Engineer's solution, here's the explanation...
Tjakka5 #6
Posted 05 April 2013 - 07:34 AM
Thanks all, this will (hopefully) work!