Read & Write a File


These are general functions that can be used to read or write any type of string data to or from a permanent text file. These make use of Lua's Io Library functions, which can be hard to understand without a template.

ReadFile

function ReadFile(FilePath)
-- HANDLE RELATIVE PATH OPTIONS.
FilePath = SKIN:MakePathAbsolute(FilePath)

-- OPEN FILE.
local File = io.open(FilePath)

-- HANDLE ERROR OPENING FILE.
if not File then
print('ReadFile: unable to open file at ' .. FilePath)
return
end

-- READ FILE CONTENTS AND CLOSE.
local Contents = File:read('*all')
File:close()

return Contents
end

ReadFileLines

Alternatively, instead of getting the entire file as a single string, you may instead want to break it down into its individual lines.

function ReadFileLines(FilePath)
-- HANDLE RELATIVE PATH OPTIONS.
FilePath = SKIN:MakePathAbsolute(FilePath)

-- OPEN FILE.
local File = io.open(FilePath)

-- HANDLE ERROR OPENING FILE.
if not File then
print('ReadFile: unable to open file at ' .. FilePath)
return
end

-- READ FILE CONTENTS AND CLOSE.
local Contents = {}
for Line in File:lines() do
table.insert(Contents, Line)
end

File:close()

return Contents
end

WriteFile

function WriteFile(FilePath, Contents)
-- HANDLE RELATIVE PATH OPTIONS.
FilePath = SKIN:MakePathAbsolute(FilePath)

-- OPEN FILE.
local File = io.open(FilePath, 'w')

-- HANDLE ERROR OPENING FILE.
if not File then
print('WriteFile: unable to open file at ' .. FilePath)
return
end

-- WRITE CONTENTS AND CLOSE FILE
File:write(Contents)
File:close()

return true
end

To merge a table of "lines" into a single string with each value on a separate line, use String = table.concat(Table, '\n')