Hey friends! I’m having a terrible time diagnosing why my game save function is either randomly crashing devices or causing 0-length save files. FYI, my save game files are json-based and can get pretty big (6-10MB+), but I’m not sure that should cause an issue. Here’s what I’ve got going on and I would most definitely appreciate any ideas!
SaveGame function - checks for valid GameID and then makes a backup of primary save file in case something goes wrong, then saves the file. Also creates an info file that shows key info about the save without having to load the whole big thing (used to show list of saves in main menu):
function SaveGame() local tmpT, y local showSave="N" local lfs = require "lfs" GameData.SaveGroup.alpha=1 timer.performWithDelay(10000, function() GameData.SaveGroup.alpha=0 end,1) if \_Game.GameID~=nil and \_Game.GameID\>0 then print("SAVING GAME!") tmpT={Team=\_Game.UserTeamID, Year=\_Game.SeasonYear, W=\_Game.Teams[\_Game.UserTeamID].Wins, L=\_Game.Teams[\_Game.UserTeamID].Losses, CW=\_Game.Teams[\_Game.UserTeamID].ConfWins, CL=\_Game.Teams[\_Game.UserTeamID].ConfLosses, C=\_Game.CoachName,R=\_Game.Teams[\_Game.UserTeamID].Rank, CY=\_Game.CareerYears} ---Copy existing table as backup local destDir = system.DocumentsDirectory -- Location where the file is stored local size = lfs.attributes (system.pathForFile( "game"..\_Game.GameID..".json", destDir ), "size") if size~=nil and size\>0 then os.remove( system.pathForFile( "game"..\_Game.GameID..".bak", destDir ) ) local result, reason = os.rename( system.pathForFile( "game"..\_Game.GameID..".json", destDir ), system.pathForFile( "game"..\_Game.GameID..".bak", destDir ) ) else os.remove( system.pathForFile( "game"..\_Game.GameID..".json", destDir ) ) end saveTable(tmpT, "game"..\_Game.GameID.."info.json") if saveTable(\_Game, "game"..\_Game.GameID..".json")==true then print("SAVED SUCCESSFULLY") else print("SAVE FAILED 1") --TRY AGAIN if saveTable(\_Game, "game"..\_Game.GameID..".json")~=true then print("SAVE FAILED 2") os.remove( system.pathForFile( "game"..\_Game.GameID..".json", destDir ) ) os.rename( system.pathForFile( "game"..\_Game.GameID..".bak", destDir ), system.pathForFile( "game"..\_Game.GameID..".json", destDir ) ) end end end end
Here’s the saveTable function that I use in the function above, as well. Yes, It’s listed in my code before that SaveGame function!
function saveTable(t, filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local file = io.open(path, "w") if file then local contents = json.encode(t) file:write( contents ) io.close( file ) --GameData.SaveGroup.alpha=0 return true else --GameData.SaveGroup.alpha=0 return false end end
