Add a file-like lua JSON wrapper

develop
lethosor 2016-04-08 17:40:14 -04:00
parent d07eb69a5e
commit 49863a9f32
1 changed files with 41 additions and 5 deletions

@ -1,5 +1,6 @@
local _ENV = mkmodule('json')
local internal = require 'json.internal'
local fs = dfhack.filesystem
encode_defaults = {
-- For compatibility with jsonxx (C++)
@ -14,11 +15,8 @@ function encode(data, options, msg)
return internal:encode(data, msg, opts)
end
function encode_file(data, path, overwrite, ...)
if dfhack.filesystem.exists(path) and not overwrite then
error('File exists: ' .. path)
end
if dfhack.filesystem.isdir(path) then
function encode_file(data, path, ...)
if fs.isdir(path) then
error('Is a directory: ' .. path)
end
local contents = encode(data, ...)
@ -41,4 +39,42 @@ function decode_file(path, ...)
return decode(contents, ...)
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
self.data = decode_file(self.path)
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