This sample code shows how to save values to a data file and use them to restore the state of an object when the app runs again.
There is a yellow box in the middle of the screen. Move it and then close the app. Open the app again and it will be where you last left it.
local myBox = display.newRect(0, 0, 40, 40) myBox:setFillColor(255, 255, 0) local function moveBox( event ) myBox.x = event.x myBox.y = event.y end local function resumeStart() -- restore previous state local path = system.pathForFile( "data.txt", system.DocumentsDirectory ) local file = io.open( path, "r" ) if file then print("loading previous state variables...") local contents = file:read( "*a" ) -- separate the variables into a table using a helper function local prevState = explode(", ", contents) myBox.x = prevState[1] myBox.y = prevState[2] io.close( file ) else myBox.x = display.stageWidth/2 myBox.y = display.stageHeight/2 end end local function onSystemEvent( event ) if( event.type == "applicationExit" ) then -- create a file to save current state local path = system.pathForFile( "data.txt", system.DocumentsDirectory ) local file = io.open( path, "w+b" ) -- save current state variables in comma separated list file:write( myBox.x ..", ".. myBox.y ) io.close( file ) end end -- explode helper function 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 table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider pos = sp + 1 -- Jump past current divider end table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider return arr end local function init() -- start and resume from previous state, if any resumeStart() myBox:addEventListener("touch", moveBox) Runtime:addEventListener( "system", onSystemEvent ) end --start the program init()
Yes? Will this still be saved during and after an update ?
Same big one question! It will save the data after an update, for example?
Great work!
Very clever!
The question above is a very good one.
Is there any better way to restore whole game screen? If we have over 10 animations are running and timers, do we have to store all frame numbers and timers? It doesn't make sense anymore :( I just want to be as it is after leaving the screen for other apps and come back later. Magic Defenders may found the better way but have no idea how they managed. If you look carefully, all small/big animations and position are exactly as I left.
is there a way to make this save a score?
Thanks for this useful code. Will this information stay saved during and after an update of an application?