Jump to content




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


  • You cannot reply to this topic
4 replies to this topic

#1 valithor

  • Members
  • 1,053 posts

Posted 05 June 2013 - 12: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.

#2 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

Posted 05 June 2013 - 12: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")


#3 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 05 June 2013 - 12: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:

#4 valithor

  • Members
  • 1,053 posts

Posted 05 June 2013 - 12: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)


#5 valithor

  • Members
  • 1,053 posts

Posted 05 June 2013 - 01:00 AM

i dont know why it worked but that fixed the saving issue





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users