I need help with a program that will right to another program but i need to set which lines it writes on. I know the following code doesnt work but it will show what i mean.
but this only writes to one line i need to chose what lines to write to and what lines not to
For now there is no `seek` function in CC-Lua, and there is no eta of if or when we will get it. The only way around this is to write out all the data to the file. For example if the file is storing 3 variables and you wish to update the 3rd one, you would need to open the file and write out all 3 variables to the file at once.
There is only one other way around it, and it's this (because I'm feeling generous today I'm going to be a code monkey)… make sure you read all comments as I explain what I am doing on each line
--# 3 things are required
--# file path
--# the line number to update
--# the replacement line
--# WARNING: this process is very long, and could take some time with really long files, avoid using this function as much as possible
--# instead aim to only write to a file when absolutely needed!
local function updateFile( _path, _lineNum, _newLine )
--# a table to hold the current lines in the file
local contents = {}
--# open the current file
local handle = fs.open( _path, 'r' )
--# make sure the file could be opened
assert( handle, "could not open file for read" )
--# load all the lines in the file into the contents table
for line in handle.readLine do
table.insert(contents, line)
end
--# close the file
handle.close()
--# make sure that the line numbers in the file go up to where we are updating
--# if we didn't do this, if we did an update on line 30, and line 30 didn't exist the file wouldn't be written properly
for i = #contents, _lineNum do
table.insert(contents, "")
end
--# replace the line in the table with the new one
contents[_lineNum] = _newLine or ""
--# open the file ready to write to
handle = fs.open( _path, 'w' )
--# make sure we could open the file
assert( handle, "could not open file for write" )
--# write to the file the contents table, here we use table.concat to put all the elements together instead of having to use a loop
handle.write( table.concat(contents, '\n') )
--# close the file
handle.close()
--# done, the file is updated
end
Hope this helps, any questions, just ask. :)/>