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

Possible to automatically edit a program?

Started by Yalani, 06 April 2014 - 09:23 AM
Yalani #1
Posted 06 April 2014 - 11:23 AM
Oh hi,

I need a way to (not manually) edit existing programs on a floppy disk.
I know I can run "shell.edit(file)" in a program, but can I also tell the computer to actually change the code?

For example:
I have a disk with a program which stores a variable

var1 = 2
and a computer with a variable

var2 = 42

can i tell the computer to replace var1 in the disk with its own var2?

Greetings
CometWolf #2
Posted 06 April 2014 - 10:09 PM
This is where the Fs API comes in
http://computercraft.info/wiki/Fs_%28API%29
You can use it to modify, read and create new files. In your case what you need would be something like

local file = fs.open("/path","w") --spcify file path and which mode to use, in this case "w" is the write mode
file.writeLine(var2) --write the variable var2 to the first line in the file, next time we use writeLine it will go on the second line.
file.close() --It's important to close the file handle once we're done with the file
Keep in mind however that to edit an existing file, you'll first need to copy it into the same file, as opening a file in write mode will clear it's contents.
RoD #3
Posted 06 April 2014 - 10:15 PM
Just adding a thing:
to read the file do:

local file = fs.open("/path", "r")
content = file.readAll()
file.close()
print(content)
The variable content now has the text that is inside the file