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

Help with files

Started by Apfeldstrudel, 09 May 2013 - 12:39 AM
Apfeldstrudel #1
Posted 09 May 2013 - 02:39 AM
Hello! I am writing two programs, one for setting up my mining turtle and one for running it.
I have made several mining turtles before but i'm trying to make it read its position from a file annd keep mining from there.
this is the mining program:

x = 1
y = 1
z = 1
facing = 1
fs.open("/mining/coords","r")
size = fs.readLine(1)
depth = fs.readLine(2)
x = h.readLine(3)
y = h.readLine(4)
z = h.readLine(5)
facing = fs.readLine(6)
--Gets the necessary variables from the file coords
function dig()
  if turtle.detect() == true then
    turtle.dig()
  end
end
function refuel()
  while turtle.getFuelLevel() <= 200 do
    if turtle.refuel() == false then
	  print("I am out of fuel, put some in the upper left slot and press enter!")
	  temp = read()
    end
  end
end
function forw()
  if turtle.forward() == true then
    refuel()
if facing == 0 then
	  x = x+1
	  h = io.open("/mining/coords", "w")
	 
    elseif facing == 1 then
	  y= y-1
	  h =io.open("/mining/coords" , "w")
    elseif facing == 2 
	  x = x + 1
	  h = io.open("/mining/coords" , "w")
    elseif facing == 3
	  y = y + 1
	  h = io.open("/mining/coords" ,"w")
    end
  else
    sleep(1)
    while turtle.forward() == false do
	  print("Cant move forward! Trying again!")
	  sleep(1)
    end
  end
end
and this is the setup program :

print("How big do you want your excavation to be?")
size = read()
print("How deep do you want it to be?")
depth =read()
print("Excavating a " .. size .." * " ..size.. " * " ..depth.. " area!(" .. tonumber(size) * tonumber(size)* tonumber(depth) .. " blocks)")
h = fs.open("/.coords","w")
h.writeLine(size)
h.writeLine(depth)
h.writeLine("1")
h.writeLine("1")
h.writeLine("1")
h.writeLine("0")
h:close()
sleep(3)
term.clear()
term.setCursorPos(1,1)
shell.run("excavate")
The thing is that i have barely touched the filesystem before and i want help.. how would i read a specific line of the file?
Engineer #2
Posted 09 May 2013 - 08:21 AM
You can literally. But I suggest you put all the lines in a table and then you can "read a specific line".
As following:


local file = fs.open("path/to/file", "r")
local fLines = {}

for lines in file.readLine do -- Not sure how this loop works, just remember it
   fLines[#fLines + 1] = lines
end

local selectedLine = fLineds[the linenumber you want to read]

This is something you know after a certain amount of time, and thats why it isnt explained very well