/traderous

To get this branch, use:
bzr branch http://66.246.75.32/bzr/traderous
1 by Josh C
zoetrope 1.4
1
-- Class: Storage
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.
7
--
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.
13
--
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
16
-- for details.
17
--
18
--
19
-- Extends:
20
--		<Class>
21
22
Storage = Class:extend{
23
	-- Property: data
24
	-- Use this property to store whatever data you like. You can
25
	-- nest tables inside this.
26
	data = {},
27
28
	-- Property: filename
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
33
	-- each other.
34
35
	filename = 'storage.dat',
36
37
	new = function (self, obj)
38
		obj = obj or {}
39
		self:extend(obj)
40
41
		if obj.filename then obj:load() end
42
43
		if obj.onNew then obj:onNew() end
44
		return obj
45
	end,
46
47
	-- Method: save
48
	-- Saves data to disk.
49
	--
50
	-- Arguments:
51
	--		none
52
	--
53
	-- Returns:
54
	--		nothing
55
56
	save = function (self, ignoreError)
57
		if ignoreError ~= false then ignoreError = true end
58
59
		local ok, message = pcall(love.filesystem.write, self.filename, dump(self.data))
60
61
		if not ok and not ignoreError then
62
			error("could not save storage from disk: " .. message)
63
		end
64
	end,
65
66
	-- Method: load
67
	-- Loads data from disk.
68
	--
69
	-- Arguments:
70
	--		ignoreError - silently ignore any errors loading, default to true
71
	--
72
	-- Returns:
73
	--		whether loading actually worked, boolean
74
75
	load = function (self, ignoreError)
76
		if ignoreError ~= false then ignoreError = true end
77
78
		local ok, data = pcall(love.filesystem.read, self.filename)
79
80
		if ok then
81
			ok, self.data = pcall(loadstring('return ' .. data))
82
			
83
			if not ok then
84
				if ignoreError then
85
					self.data = {}
86
				else
87
					error("could not deserialize storage data: " .. self.data)
88
				end
89
			end
90
		else
91
			if not ignoreError then
92
				error("could not load storage from disk: " .. data)
93
			end
94
		end
95
96
		return ok
97
	end
98
}