Last active
December 9, 2020 03:27
-
-
Save skrolikowski/b62d866f2edf2455dd4a340011e62298 to your computer and use it in GitHub Desktop.
Save Module for Love2D (with merging)
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
-- Love2D initialization | |
-- | |
function love.load() | |
loadGame('my-game') | |
end | |
---- ---- ---- ---- | |
-- New Game | |
-- | |
function newGame(name) | |
SAVE = Saver:save(name, { | |
-- initial game data | |
-- ... | |
}) | |
end | |
-- Load Game | |
-- | |
function loadGame(name) | |
if Saver:exists(name) then | |
SAVE = Saver:load(name) | |
else | |
newGame(name) | |
end | |
end | |
-- Save Game | |
-- | |
function saveGame(name, data) | |
SAVE = Saver:save(name, merge(SAVE, data)) | |
end | |
-- merge two nested tables, in place | |
function merge(t1, t2) | |
for k, v in pairs(t2) do | |
if type(v) == 'table' then | |
t1[k] = merge(t1[k], t2[k]) | |
else | |
t1[k] = v | |
end | |
end | |
return t1 | |
end |
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
-- Binser is a lua serializer: https://github.com/bakpakin/binser | |
local Binser = 'vendor.binser.binser' | |
local Saver = {} | |
-- Write to save file | |
-- | |
function Saver:save(name, data) | |
love.filesystem.write(name .. '.txt', Binser.serialize(data)) | |
return data | |
end | |
-- Load save file | |
-- | |
function Saver:load(name) | |
if self:exists(name) then | |
local data, size = love.filesystem.read(name .. '.txt') | |
return Binser.deserialize(data)[1] | |
end | |
return false | |
end | |
-- File exists? | |
-- | |
function Saver:exists(name) | |
return self:getInfo(name) ~= nil | |
end | |
-- Get file info | |
-- | |
function Saver:getInfo(name) | |
return love.filesystem.getInfo(name .. '.txt', 'file') | |
end | |
return Saver |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment