What you will need to do is store the time that the app is closed. Then when the app is opened compare the current time to the stored time, and calculate how much “power” you need to deduct.
local function onSystemEvent( event ) if event.type == "applicationStart" or event.type == "applicationResume" then local now = os.time() local exitTime = loadTheTimeFromSavedJsonFile() if exitTime == nil then exitTime = now end local timeBetweenSessions = os.difftime( now, exitTime ) local powerToDrainPerSecond = 1 local power = loadPowerFromSavedJsonFile() power = power - (powerToDrainPerSecond \* timeBetweenSessions) elseif event.type == "applicationExit" or event.type == "applicationSuspend" then local exitTime = os.time() saveTheTimeToJsonFile(exitTime) end end Runtime:addEventListener( "system", onSystemEvent )
In this example, I save the time when the user leaves the app, and also the current amount of power. There are plenty of examples about how to save data to json files or whatever method you fancy using, so I won’t explain them here.
Then when the app restarts, you find out how much time has passed, load the previous amount of power, and then adjust the amount of power based on the amount of time that has passed. I’ve kept it as simple as possible, and removed 1 power per second that the game was closed. Depending on how your game works you might want to only remove power for every minute/hour/etc that has passed, so you’d need to find out how many minutes/hours have passed by dividing the number of seconds.
Edit: I added a catch so that the first time the app is ever opened, it will just set the “exitTime” to be the same as “now”. That way the time difference will be 0s, and no power will be removed. It also means you avoid nil errors if the stored time does not exist.