Im trying to save and load high scores in my game. Here is what I have:
ego.lua
[lua]–Save function
function saveFile( fileName, fileData )
–Path for file
local path = system.pathForFile( “highscore.txt”, system.DocumentsDirectory )
–Open the file
local file = io.open( path, “w+” )
–Save specified value to the file
if file then
file:write( fileData )
io.close( file )
end
end
–Load function
function loadFile( fileName )
–Path for file
local path = system.pathForFile( “highscore.txt”, system.DocumentsDirectory )
–Open the file
local file = io.open( path, “r” )
–If the file exists return the data
if file then
local fileData = file:read( “*a” )
io.close( file )
return fileData
–If the file doesn’t exist create it and write it with “empty”
else
file = io.open( path, “w” )
file:write( “empty” )
io.close( file )
return “empty”
end
end[/lua]
And in the game I have:
[lua]ego = require “ego”
saveFile = ego.saveFile
loadFile = ego.loadFile
score = 0
local scoreText = display.newText(score,display.contentCenterX, 150, “Helvetica”, 58)
scoreText:setFillColor(0,0,0)
local function addToScore()
score = score + 1
scoreText.text = score
end
highscore = loadFile (“highscore.txt”)
local function checkForFile ()
if highscore == “empty” then
highscore = 0
saveFile(“highscore.txt”, highscore)
end
end
checkForFile()
local function onSystemEvent ()
if score > tonumber(highscore) then --We use tonumber as highscore is a string when loaded
saveFile(“highscore.txt”, score)
end
end
[/lua]
when I have it display the “high score” it only displays the current score.