Jump to content




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


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

#1 Cranium

    Ninja Scripter

  • Moderators
  • 4,031 posts
  • LocationLincoln, Nebraska

Posted 21 September 2012 - 05: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?

#2 sjele

  • Members
  • 334 posts
  • LocationSomewhere on the planet called earth

Posted 21 September 2012 - 05: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

#3 MysticT

    Lua Wizard

  • Members
  • 1,597 posts

Posted 21 September 2012 - 05: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")


#4 Cranium

    Ninja Scripter

  • Moderators
  • 4,031 posts
  • LocationLincoln, Nebraska

Posted 21 September 2012 - 05:55 PM

I wanted to avoid tables, but it sounds like that's the easiest way to do it. Thanks guys!





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users