Jump to content




Getting single line from loaded file (fs)


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

#1 Waitdev_

  • Members
  • 432 posts
  • LocationAdelaide

Posted 18 October 2015 - 03: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 by Wait_, 18 October 2015 - 03:04 AM.


#2 valithor

  • Members
  • 1,053 posts

Posted 18 October 2015 - 03: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 by valithor, 18 October 2015 - 03:54 AM.


#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 18 October 2015 - 04: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


#4 Waitdev_

  • Members
  • 432 posts
  • LocationAdelaide

Posted 18 October 2015 - 08: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





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users