readlines

function readlines( filename ) --> strlst, err

Description

Reads the full content of a file into a string list.

Parameters

filename

Path to the file that should be read.

Return Values

strlst

The lines in the file or nil if an error occurse.

err

A message if an error occurse otherwise nil.

Code

--ZFUNC-readlines-v1
local function readlines( filename ) --> strlst, err
   --ZFUNC-lines-v1
   local function lines( str )
      if not str:find( "\n$" ) then str = str.."\n" end
      return str:gmatch( "([^\n]*)\n" )
   end

   local f, err = io.open( filename, "r" )
   if err then return nil, err end

   local str, err = f:read( "*a" )
   if err then return nil, err end

   local strlst = {}
   for line in lines( str ) do
      table.insert( strlst, line )
   end

   local res, err = f:close()
   if err then return nil, err end

   return strlst
end

return readlines

Examples

local t = require( "taptest" )
local readlines = require( "readlines" )
local same = require( "same" )

f = io.open( "ReadLinesXmpl.txt", "w" )
f:write( "a ", "long ", "text\n\n", "is ", 1337 )
f:close()

strlst, err = readlines( "ReadLinesXmpl.txt" )
t( same( strlst, { "a long text", "", "is 1337" } ), true )

os.remove( "ReadLinesXmpl.txt" )

t()