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

Reading the lines from a file

Started by Neander_King, 02 June 2015 - 11:19 PM
Neander_King #1
Posted 03 June 2015 - 01:19 AM
I am trying to iterate through all the lines in a file and return a table containing the text from each line, in order.

function getNotes()
  local f = fs.open("example", "r")
  local end_reached = false
  local notes = {}
  while not end_reached do
	local current_note = f.readline()
	if current_note ~= nil then
	  notes.insert(current_note)
	else
	  end_reached = true
	end
  end
  f.close()
  return notes
end

print(textutils.serialize(getNotes()))

However, this gives an attempt to call nil error on line 6, and I see nothing wrong with doing f.readline(). Please tell me if there is a proper way to read all the lines of a file.
InDieTasten #2
Posted 03 June 2015 - 01:25 AM
the error is at notes.insert. It should either be notes:insert(…) or table.insert(notes, …)

and it's called readLine, not readline
Edited on 02 June 2015 - 11:26 PM
Neander_King #3
Posted 03 June 2015 - 01:26 AM
Cannot believe I forgot that. Thank you!
InDieTasten #4
Posted 03 June 2015 - 01:28 AM
no problem ;)/>
Bomb Bloke #5
Posted 03 June 2015 - 01:35 AM
For what it's worth, io.lines() makes things a bit easier:

local function getNotes()
  local notes = {}
  for current_note in io.lines("exampleFile") do
        table.insert(notes, current_note)
  end
  return notes
end
InDieTasten #6
Posted 03 June 2015 - 01:36 AM
For what it's worth, io.lines() makes things a bit easier:

local function getNotes()
  local notes = {}
  for current_note in io.lines("exampleFile") do
		table.insert(notes, current_note)
  end
  return notes
end
nice catch +1