I have some spaghetti code that I use to read high scores (just a list of comma separated values) into a table, and to output those values from the table into a text file.
[lua]local function saveData(scores, path)
local tempString = scores[1]
for i=2,13,1 do
tempString = (tempString … “,” … scores[i])
end
tempString = (tempString … “,” … releaseNum … “,” … versionNum … “,” … buildNum )
local file = io.open( path, “w” )
file:write( tempString )
io.close( file )
return true
end
local filePath = system.pathForFile( “hiScores”, system.DocumentsDirectory )
saveData(hiScoreTable, filePath)[/lua]
I can’t remember why I build my string that way, but it works so I’l happy with not touching it! And I have separate release, version, and build values that I save into the high scores file so that I can tell how old it is in case I ever need to convert it to a new format or clear high scores for a given level.
To read the file back, I make sure it exists and then have a similar function.
[lua]local function explode(div,str)
if (div==’’) then return false end
local pos,arr = 0,{}
– for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
– Insert chars left of current divider
table.insert(arr, string.sub(str,pos,st-1))
pos = sp + 1 – Jump past current divider
end
– Attach chars right of last divider
table.insert(arr,string.sub(str,pos))
return arr
end
local loadHighScores = function( strFilename )
local path = system.pathForFile( strFilename, system.DocumentsDirectory )
local file = io.open( path, “r” )
if file then
– read all contents of file into a string
local line = file:read( “*a” )
– explode string into entries in a table
local contents = explode(",", line)
io.close( file )
end
return contents
end
local hiScoreTable = loadHighScores(“hiScores”)[/lua]
The explode function is the magic sauce (which I didn’t create) that I use for loading levels (which are huge comma delimited files) and high scores. Once I had the explode function and was comfortable with it, saving scores became as simple as updating values in a table.
After the game, I compare the player scores against the appropriate entry in the hiScoreTable, and if the player score is higher, then I change that value in my hiScoreTable (I also score the date of the score, so I change that too) and then I run saveData(hiScoreTable). [import]uid: 14598 topic_id: 21978 reply_id: 87375[/import]