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

Getting single line from loaded file (fs)

Started by Waitdev_, 18 October 2015 - 02:03 AM
Waitdev_ #1
Posted 18 October 2015 - 04:03 AM
It's pretty simple, all i need to do is make a program read a single given line from a file loaded by fs/http (multi-line string)
for example, i could do:

--#-------Code-------#--
function getLine(file,line)
  fs.open(file,"r")
  --#code
end
getLine("ExFile",4)
--#-------ExFile-------#--
hello
words and words
w0rds w1th  @ch4r4ct3rs
last line 9i94539 with characters, "quotes" and spaces.
#needs to read all those
again, it needs to be able to get anything from that line. it's mainly so i can make an updater without multiple pastebin files, but just 1 file for all of my programs to update.

basically, it's designed for having pastebin codes in a pastebin file and reading all the codes to check if there's a difference and what it needs to update. yes, its for an OS.

so, how can i do this?
Edited on 18 October 2015 - 02:04 AM
valithor #2
Posted 18 October 2015 - 04:48 AM
You could do something like this:


for i = 1, line-1 do
  value = value:match(".?.-\n(.*)")
end
value = value:match("(.?.-)\n") or value

Where line is the line you want, and value is the thing you got from http/fs
Edited on 18 October 2015 - 02:54 AM
Bomb Bloke #3
Posted 18 October 2015 - 05:32 AM
Both the handles returned by http.get() and fs.open() have the function readLine() attached to them, so this isn't particularly difficult; the only catch is that you have to read the input streams in order. If you want to seek backwards, you need to close the handle and open a new one.

local function getLine(file, line)
  local input, output = fs.open(file, "r")

  for i = 1, line do
    output = input.readLine()
  end

  input.close()

  return output
end

A better solution would be to just load the whole file into a table:

local function loadFile(file)
  local output = {}

  for line in io.lines(file) do
    output[#output + 1] = line
  end

  return output
end
Waitdev_ #4
Posted 18 October 2015 - 09:46 AM
thanks for your help guys, now i can come back to this whenever i want to make something read lines and learn it that way ;)/>
or i'll just put it in my api xD