forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.lua
More file actions
90 lines (78 loc) · 1.98 KB
/
json.lua
File metadata and controls
90 lines (78 loc) · 1.98 KB
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
85
86
87
88
89
90
local _ENV = mkmodule('json')
local internal = require('json.internal')
local fs = dfhack.filesystem
encode_defaults = {
-- For compatibility with jsonxx (C++)
pretty = true,
indent = '\t',
}
function encode(data, options, msg)
local opts = {}
for k, v in pairs(encode_defaults) do opts[k] = v end
for k, v in pairs(options or {}) do opts[k] = v end
return internal:encode(data, msg, opts)
end
function encode_file(data, path, ...)
if fs.isdir(path) then
error('Is a directory: ' .. path)
end
local contents = encode(data, ...)
local f = io.open(path, 'w')
if not f then
error('Could not write to ' .. tostring(path))
end
f:write(contents)
f:close()
end
function decode(data, msg)
return internal:decode(data, msg)
end
function decode_file(path, ...)
local f = io.open(path)
if not f then
error('Could not read from ' .. tostring(path))
end
local contents = f:read('*all')
f:close()
return decode(contents, ...) or {}
end
local _file = defclass()
function _file:init(opts)
self.path = opts.path
self.data = {}
self.exists = false
self:read(opts.strict)
end
function _file:read(strict)
if not fs.exists(self.path) then
if strict then
error('cannot read file: ' .. self.path)
else
self.data = {}
end
else
self.exists = true
local ok, err = pcall(function() self.data = decode_file(self.path) end)
if not ok then
if strict then
error(('cannot decode file: %s: %s'):format(self.path, err))
end
self.data = {}
end
end
return self.data
end
function _file:write(data)
if data then
self.data = data
end
encode_file(self.data, self.path)
self.exists = true
end
function _file:__tostring()
return ('<json file: %s>'):format(self.path)
end
function open(path, strict)
return _file{path=path, strict=strict}
end
return _ENV