-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhighscore.lua
More file actions
84 lines (56 loc) · 1.47 KB
/
highscore.lua
File metadata and controls
84 lines (56 loc) · 1.47 KB
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
module (..., package.seeall)
-- highscore file
local path = system.pathForFile( "flyingSquirrelHS.txt", system.DocumentsDirectory )
function getHighScore()
-- io.open opens a file at path. returns nil if no file found
local fh, reason = io.open( path, "r" )
local score = 0
if fh then
-- if file exists read highscore from file
score = fh:read( "*n" )
else
-- display failure message in terminal
print( "Reason open failed: " .. reason )
-- create file because it doesn't exist yet
fh = io.open( path, "w" )
if fh then
print( "Created file" )
else
print( "Create file failed!" )
end
fh:write( "0" )
end
io.close( fh )
return score
end
function saveHighScore( score )
-- io.open opens a file at path. returns nil if no file found
local fh, reason = io.open( path, "w" )
if fh then
-- if file exists read highscore from file
fh:write( score )
else
-- display failure message in terminal
print( "Reason open failed: " .. reason )
-- create file because it doesn't exist yet
fh = io.open( path, "w" )
if fh then
print( "Created file" )
else
print( "Create file failed!" )
end
fh:write( score )
end
io.close( fh )
end
function checkHighscore( score )
-- retrieve old high score
local oldHighScore = getHighScore()
if score > oldHighScore then
-- new high score
saveHighScore( score )
return true
else
return false
end
end