Last active
November 16, 2019 10:13
-
-
Save SibGent/e14ab18d1c31c4d3bd36169c00a65df4 to your computer and use it in GitHub Desktop.
Corona SDK SaveManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local M = {} | |
local json = require("json") | |
local config | |
local FILENAME = "save" | |
local BASE_DIR = system.DocumentsDirectory | |
local SAVE = {} | |
local initConfig | |
, getKeysByLine | |
function M.init(options) | |
config = options.config | |
end | |
function M.load() | |
local file = io.open(system.pathForFile(FILENAME, BASE_DIR), "r") | |
if file then | |
local content = file:read("*a") | |
SAVE = json.decode(content) | |
if not SAVE then | |
SAVE = {} | |
native.showAlert("Warning", "save file is corrupted", {"OK"}) | |
end | |
io.close(file) | |
end | |
initConfig() | |
end | |
function M.save() | |
local path = system.pathForFile(FILENAME, BASE_DIR) | |
local file = io.open(path, "w+") | |
if file then | |
local encoded = json.encode(SAVE, { indent = true }) | |
file:write(encoded) | |
io.close(file) | |
end | |
end | |
function M.keyExists(line) | |
local keys = getKeysByLine(line) | |
local value | |
for i = 1, #keys do | |
local key = keys[i] | |
if value ~= nil then | |
value = value[key] | |
else | |
value = SAVE[key] | |
end | |
end | |
return (value ~= nil) and true or false | |
end | |
function M.setValue(line, value) | |
local keys = getKeysByLine(line) | |
local link = nil | |
for i = 1, #keys - 1 do | |
local key = keys[i] | |
if link then | |
link[key] = link[key] or {} | |
link = link[key] | |
else | |
SAVE[key] = SAVE[key] or {} | |
link = SAVE[key] | |
end | |
end | |
if link then | |
link[keys[#keys]] = value | |
else | |
SAVE[keys[1]] = value | |
end | |
end | |
function M.getValue(line) | |
local keys = getKeysByLine(line) | |
local value = SAVE[keys[1]] | |
if not value then | |
return value | |
end | |
for i = 2, #keys do | |
local key = keys[i] | |
value = value[key] | |
if not value or type(value) ~= "table" then | |
return value | |
end | |
end | |
return value | |
end | |
function initConfig() | |
for k, v in pairs(config) do | |
if not M.keyExists(k) then | |
M.setValue(k, v) | |
end | |
end | |
end | |
function getKeysByLine(line) | |
local keys = {} | |
for key in line:gmatch("[^%.]+") do | |
keys[1 + #keys] = key | |
end | |
return keys | |
end | |
return M |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment