-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataSaver.lua
96 lines (78 loc) · 1.94 KB
/
dataSaver.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
--DATASAVER
--Save score data in JSON format
module(..., package.seeall)
require "json"
function saveValue(key, value)
--temp variable
local app
local filename = "app.data"
local base = system.ResourceDirectory
local path = system.pathForFile( filename, base )
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
app = json.decode(contents)
io.close( file )
if(not app.data) then
app.data = {}
end
app.data[key] = value
contents = json.encode(app)
local file = io.open( path, "w" )
file:write( contents )
io.close( file )
else
--if file doesn't exist
--create default structure
app = {data = {}}
app.data[key] = value
local contents = json.encode(app)
local file = io.open( path, "w" )
file:write( contents )
io.close( file )
end
end
function loadValue(key)
--temp variable
local app
local filename = "app.data"
local base = system.ResourceDirectory
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
local file = io.open( path, "r" )
if file then
--read contents
local contents = file:read( "*a" )
app = json.decode(contents)
if(not app.data) then app.data = {}; end
return app.data[key]
end
return nil
end
function save( filename, dataTable )
filename = filename..".json"
--encode table into json string
local jsonString = json.encode( dataTable )
-- create a file path for corona i/o
local path = system.pathForFile( filename, system.ResourceDirectory )
local file = io.open( path, "w" )
if file then
file:write( jsonString )
io.close( file )
end
end
function load( filename )
filename = filename..".json"
local base = system.ResourceDirectory
local path = system.pathForFile( filename, base )
local contents
local file = io.open( path, "r" )
if file then
contents = file:read( "*a" )
io.close( file )
return json.decode( contents )
else
return nil
end
end