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

[Solved] [Lua] writeLine() deleting file contents

Started by valithor, 04 June 2013 - 11:47 PM
valithor #1
Posted 05 June 2013 - 01:47 AM
So i am attempting to make a coordinates system for a mining turtle and came across a problem when testing one of the basic functions that record when the turtle moves.

function file()
  if not fs.exists("coord") then
	w = fs.open("coord","w")
	w.writeLine("0")
	w.close()
  end
end
-- this is where my problem is it erases anything that was in
-- the file
function save()
  s = fs.open("coord","w")
  s.writeLine(x)
  s.close()
end
local x = tonumber(0)
if turtle.forward()==true then
  file()
  x = x+1
  save()
end
print(x)

I have seen the writeLine used before to store coordinates and have no idea why it isn't working. Any help would be appreciated.
Kingdaro #2
Posted 05 June 2013 - 01:51 AM
You're opening files with write mode and not append mode. This line:

w = fs.open("coord","w")

and other subsequent lines should be this:

w = fs.open("coord","a")
theoriginalbit #3
Posted 05 June 2013 - 01:54 AM
writeLine is not what it removing file contents. it is the way you're opening the file. there are 3 file modes you can use, as follows;
'r' — opens the file in read-only mode
'w' — opens the file in write mode, only writes what is in current buffer to file when the handle is closed (can also write to file with flush), overwriting existing contents
'a' — opens the file in append mode, writes the buffer to file at the end of the existing contents.

EDIT: oh the ninja's… :ph34r:/>
valithor #4
Posted 05 June 2013 - 01:58 AM
it is really weird i changed the code by just moving the local x = 0 up above the save function and now it works

function file()
  if not fs.exists("coord") then
    w = fs.open("coord","w")
    w.writeLine("0")
    w.close()
  end
end
local x = 0
function save()
  s = fs.open("coord","w")
  s.writeLine(x)
  s.close()
end
if turtle.forward()==true then
  file()
  x = x+1
  save()
end
print(x)
valithor #5
Posted 05 June 2013 - 02:00 AM
i dont know why it worked but that fixed the saving issue