2
-- Allows your app to save data between sessions -- high scores or game
3
-- progress, for example. A single storage instance corresponds to a
4
-- file on disk. If you'd like to maintain individual files (e.g. so
5
-- a user can email a save game to a friend), you'll need to create a
6
-- separate storage instance for each one.
8
-- Your data is saved on disk in Lua format. This means that if someone
9
-- figures out where your data files are saved, it is very trivial for them
10
-- to change the data. If saving or loading fails, then this class still
11
-- retains your data across a single app session. If you want to be notified
12
-- when errors occur, check the <save()> and <load()> methods' arguments.
14
-- Make sure to set your app's identity in conf.lua, so that your
15
-- files don't clobber some other app's. See https://love2d.org/wiki/Config_Files
22
Storage = Class:extend{
24
-- Use this property to store whatever data you like. You can
25
-- nest tables inside this.
29
-- What filename to store the data on disk under. See
30
-- https://love2d.org/wiki/love.filesystem for where exactly this
31
-- will be saved. Make sure to set this if your app is using
32
-- multiple storage objects -- otherwise they will overwrite
35
filename = 'storage.dat',
37
new = function (self, obj)
41
if obj.filename then obj:load() end
43
if obj.onNew then obj:onNew() end
48
-- Saves data to disk.
56
save = function (self, ignoreError)
57
if ignoreError ~= false then ignoreError = true end
59
local ok, message = pcall(love.filesystem.write, self.filename, dump(self.data))
61
if not ok and not ignoreError then
62
error("could not save storage from disk: " .. message)
67
-- Loads data from disk.
70
-- ignoreError - silently ignore any errors loading, default to true
73
-- whether loading actually worked, boolean
75
load = function (self, ignoreError)
76
if ignoreError ~= false then ignoreError = true end
78
local ok, data = pcall(love.filesystem.read, self.filename)
81
ok, self.data = pcall(loadstring('return ' .. data))
87
error("could not deserialize storage data: " .. self.data)
91
if not ignoreError then
92
error("could not load storage from disk: " .. data)