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

Create and read config files

Started by DvgCraft, 28 December 2014 - 12:52 PM
DvgCraft #1
Posted 28 December 2014 - 01:52 PM
Hello, I am making an OS and I want to make something that the user can store its settings in one file. I searched on internet an I could'nt find a simple solution without any external APIs or programs.

So, how can I make a config file and edit a single line of it? I know how to edit a whole program, but not a single line.
Maybe it is possible to write the config file as a table and read it as an API?

I hope you can help me.

(I want to UNDERSTAND the code, so please explain everything ;)/> )
theoriginalbit #2
Posted 28 December 2014 - 01:56 PM
take a look at my programs (link in signature) I have an API called ccConfig, make sure to look at the documentation on how to use it.
DvgCraft #3
Posted 28 December 2014 - 02:02 PM
I've seen that one but I want to write the code myself without other APIs from internet. I want to understand what I'm doing… maybe you could explayn your code?

I've seen that API, but I want to understand the code I'm using. Maybe you could explain it?
Thanks!
Edited on 28 December 2014 - 01:37 PM
Bomb Bloke #4
Posted 28 December 2014 - 02:35 PM
Long story short, there's no method (within ComputerCraft) of opening a file and editing just a part of it. You need to load the whole file into memory (RAM), alter it there, and then re-write the entire thing back to disk.
Exerro #5
Posted 28 December 2014 - 02:57 PM
Long story short, there's no method (within ComputerCraft) of opening a file and editing just a part of it. You need to load the whole file into memory (RAM), alter it there, and then re-write the entire thing back to disk.
To expand on this…
Let's say you want to change line 5 of a file. Rather than saying "write to line 5", you need to read the entire contents of the file, change line 5, then write everything back in. You can use this by using h.readLine().

local lines = {}
local h = fs.open( path, "r" )
for line in h.readLine do
    lines[#lines+1] = line
end
h.close()
Now you have a table of the lines of a file. Line 1 would be lines[1].
You can also change an individual line by doing lines = x.

To update the file you got it from, you need to write back all the lines that you read (and potentially modified):

local h = fs.open( path, "w" )
for i = 1, #lines do
    h.writeLine( lines[i] )
end
h.close()
DvgCraft #6
Posted 28 December 2014 - 03:16 PM
Thank you very much, awsumben13! That is what I'm looking for. So simple! :D/>