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

[API] How to read the number of lines from a file

Started by Cranium, 21 September 2012 - 04:32 PM
Cranium #1
Posted 21 September 2012 - 06:32 PM
I am working on my logging function to log actions taken on the terminal, but I need to have it only write about 25 lines, and then scroll the last 25 actions. So I am thinking that I need it to check if the number of lines in the file is over 25, and if so, delete the first line. How would I do that?
sjele #2
Posted 21 September 2012 - 06:41 PM
Try using tables? Then just make the table go to 25, and each time a new action happens re-write the file, using the table
MysticT #3
Posted 21 September 2012 - 06:42 PM
You have to read the whole file line by line and count them:

local file = fs.open(path, "r")
if file then
  local i = 0
  while file.readLine()
    i = i + 1
  end
  file.close()
  print("Lines in the file: ", i)
end

You could also load it in a table and then get it's size to know the number of lines. It would be better to have the log on a table and writing it to the file each time you modify it. Something like:

local log = {}

local function loadLog()
  local file = fs.open("log.txt", "r")
  if file then
    log = {}
    local line = file.readLine()
    while line do
	  table.insert(log, line)
	  line = file.readLine()
    end
    file.close()
  end
end

local function saveLog()
  local file = fs.open("log.txt", "w")
  if file then
    for _,line in ipairs(log) do
	  file.writeLine(line)
    end
    file.close()
  end
end

local function addLogEntry(s)
  table.insert(log, s)
  while #log > 25 do
    table.remove(log, 1)
  end
  saveLog()
end

loadLog()
addLogEntry("Log opened")
Cranium #4
Posted 21 September 2012 - 06:55 PM
I wanted to avoid tables, but it sounds like that's the easiest way to do it. Thanks guys!