-
Notifications
You must be signed in to change notification settings - Fork 1
/
file_helper.lua
84 lines (64 loc) · 1.91 KB
/
file_helper.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
local QIT = require "QIT"
---@class file_helper
local file = {}
--- Return a table of lines from a file.
---@param filename string The file to be read.
---@param default string[]? The value returned when the file does not exist.
---@return string[] lines
function file.getLines(filename, default)
local lines = QIT()
if not fs.exists(filename) then
return default or {}
end
for line in io.lines(filename) do
lines:Insert(line)
end
return lines:Clean()
end
--- Return a string containing the entirety of the file read.
---@param filename string The file to be read.
---@param default string? The value returned when the file does not exist.
---@return string data
function file.getAll(filename, default)
local h = io.open(filename, 'r')
if not h then
return default or ""
end
local data = h:read "*a"
h:close()
return data
end
--- Write data to a file
---@param filename string The file to write to.
---@param data string The data to write.
function file.write(filename, data)
local h, err = io.open(filename, 'w')
if not h then
error(("Failed to open '%s' for writing."):format(err), 2)
end
h:write(data):close()
end
--- Return a string containing the entirety of the file read.
---@param filename string The file to be read.
---@param default any The value returned when th e file does not exist.
---@return any data
function file.unserialize(filename, default)
local h = io.open(filename, 'r')
if not h then
return default or ""
end
local data = textutils.unserialise(h:read "*a")
h:close()
return data
end
--- Write data to a file
---@param filename string The file to write to.
---@param data any The data to write, this will be serialized.
function file.serialize(filename, data)
local h, err = io.open(filename, 'w')
if not h then
error(("Failed to open '%s' for writing."):format(err), 2)
end
h:write(textutils.serialize(data)):close()
end
return file