Load Text File into a Table (code snippet)

Description

Loads a file into a table and returns it. If the file fails to open, returns false as the first parameter and an error message in the second one.

Requires: None

Code

LoadFileToArray.fh_lua
function fileToArray(filename)
    local file = io.open(filename)
    local tbllines = {}
    if file then
        for line in file:lines() do
            table.insert(tbllines,line)
        end
        file:close()
        return tbllines
    else
        return false,'File Failed To Open'
    end
end

Usage

local lines,err = fileToArray('d:\\temp\\license.txt')
if lines then
    print (#lines)  -- Prints number of lines in the file
    for k,v in ipairs(lines) do  -- to process contents
        print(k,v)
    end
else
    print(err)
end