helpers: improved i/o functions
This commit is contained in:
parent
e81f46950b
commit
92d17d289c
1 changed files with 35 additions and 39 deletions
74
helpers.lua
74
helpers.lua
|
@ -33,53 +33,49 @@ end
|
||||||
|
|
||||||
-- {{{ File operations
|
-- {{{ File operations
|
||||||
|
|
||||||
-- see if the file exists and is readable
|
-- check if the file exists and is readable
|
||||||
function helpers.file_exists(file)
|
function helpers.file_exists(path)
|
||||||
local f = io.open(file)
|
local file = io.open(path, "rb")
|
||||||
if f then
|
if file then file:close() end
|
||||||
local s = f:read()
|
return file ~= nil
|
||||||
f:close()
|
|
||||||
f = s
|
|
||||||
end
|
|
||||||
return f ~= nil
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- get all lines from a file, returns an empty
|
-- get a table with all lines from a file
|
||||||
-- list/table if the file does not exist
|
function helpers.lines_from(path)
|
||||||
function helpers.lines_from(file)
|
local lines = {}
|
||||||
if not helpers.file_exists(file) then return {} end
|
for line in io.lines(path) do
|
||||||
local lines = {}
|
lines[#lines + 1] = line
|
||||||
for line in io.lines(file) do
|
end
|
||||||
lines[#lines + 1] = line
|
return lines
|
||||||
end
|
|
||||||
return lines
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- match all lines from a file, returns an empty
|
-- get a table with all lines from a file matching regexp
|
||||||
-- list/table if the file or match does not exist
|
function helpers.lines_match(regexp, path)
|
||||||
function helpers.lines_match(regexp, file)
|
local lines = {}
|
||||||
local lines = {}
|
for line in io.lines(path) do
|
||||||
for index,line in pairs(helpers.lines_from(file)) do
|
if string.match(line, regexp) then
|
||||||
if string.match(line, regexp) then
|
lines[#lines + 1] = line
|
||||||
lines[index] = line
|
end
|
||||||
end
|
end
|
||||||
end
|
return lines
|
||||||
return lines
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- get first line of a file, return nil if
|
-- get first line of a file
|
||||||
-- the file does not exist
|
function helpers.first_line(path)
|
||||||
function helpers.first_line(file)
|
local file, first = io.open(path, "rb"), nil
|
||||||
return helpers.lines_from(file)[1]
|
if file then
|
||||||
|
first = file:read("*l")
|
||||||
|
file:close()
|
||||||
|
end
|
||||||
|
return first
|
||||||
end
|
end
|
||||||
|
|
||||||
-- get first non empty line from a file,
|
-- get first non empty line from a file
|
||||||
-- returns nil otherwise
|
function helpers.first_nonempty_line(path)
|
||||||
function helpers.first_nonempty_line(file)
|
for line in io.lines(path) do
|
||||||
for k,v in pairs(helpers.lines_from(file)) do
|
if #line then return line end
|
||||||
if #v then return v end
|
end
|
||||||
end
|
return nil
|
||||||
return nil
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- }}}
|
-- }}}
|
||||||
|
|
Loading…
Add table
Reference in a new issue