Simple Easy Timer Question

How do I make a timer that times how long the player is playing the level of a game. I think you have to start timer and then I want the time to be saved to a variable. Thanks for help!

Hi,

A good way to do this is to keep track of time using os.time...

Store that to a variable...and then use an "enterFrame" event listener that increments the seconds spent in the level.

Sure, you can use the timer functions...but I would be careful about it...since it was not completely stable the last time I used it.

So...use the "enterFrame" event listener...

You can do something like this in your code...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
local startTime
 
-- Bonus code to format the time...makes the time elapsed 
--    look better to the player
function formatTime(timeInSeconds)
 
local hoursLeft  = math.floor(timeInSeconds / 3600)
local minutesLeft = math.floor((timeInSeconds - hoursLeft*3600)/60)
local secondsLeft = (timeInSeconds - hoursLeft*3600 - minutesLeft*60)
 
 local finalTimeString = ""
 if(hoursLeft > 0) then
        finalTimeString = hoursLeft..[[h:]]
 
 end
 
 if(minutesLeft == 0 and hoursLeft == 0) then 
 else
        finalTimeString = finalTimeString..minutesLeft..[[m:]]
 end
 
  finalTimeString = finalTimeString..secondsLeft..[[s]]
 
return finalTimeString
 
end
 
local function showTimer()
   local currentTime = os.time()
 
   local elapsedTime = currentTime - startTime
   -- added bonus, you can also format the time with this 
   --      function :)
 
   local elapsedTimeString
   elapsedTimeString = formatTime(elapsedTime)
 
end
 
-- This is code you add to the initialization of the
--    screen/scene
function new()
.
.
.
        startTime = os.time()
        Runtime:addEventListener("enterFrame", showTimer)
.
.
.
end
views:1413 update:2011/10/2 9:44:12
corona forums © 2003-2011