diff --git a/library/lua/json.lua b/library/lua/json.lua index bcb86537c..ac7aa6327 100644 --- a/library/lua/json.lua +++ b/library/lua/json.lua @@ -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 (''):format(self.path) +end + +function open(path, strict) + return _file{path=path, strict=strict} +end + return _ENV