Is there a better way to implement a timer for display in gui than this? (SOLVED)

Hi guys, I want to set up a simple timer that counts up in seconds and minutes i.e. I don’t want it to go from 0:59 to 0:60 etc. I want it to go 0:59 to 1:00.

I figured out a messy and somewhat inaccurate way to get it going, but I’m still quite new to programming and I’m thinking there must be a less convoluted, more accurate way to do this. Here’s what I’ve got…

-- hud.gui_script

function init(self)
 --clock stuff
    self.seconds = gui.get_node("seconds")
    self.minutes = gui.get_node("minutes")
    self.zero = gui.get_node("zero")
    self.minute_tracker = 0
    self.tick = 0
end

function update(self, dt)
     self.tick = self.tick + dt
        -- so I don't show milliseconds...
	local tick_rounded = math.floor(self.tick) 
	gui.set_text(self.seconds, tostring(tick_rounded))	
	if tick_rounded == 10 then
		self.tick = self.tick + dt
		tick_rounded = math.floor(self.tick)
		gui.set_text(self.seconds, tostring(tick_rounded))
		--local pos = gui.get_position(self.seconds)
		--pos.x = pos.x - 5*dt
		--gui.set_position(self.seconds, pos)
		gui.set_enabled(self.zero, false)
	end
	if self.tick >= 59.9833334367722 then --trying to get as close to transition to a minute as a I can
		self.tick = 0 
		self.minute_tracker = self.minute_tracker + 1
		gui.set_text(self.minutes, tostring(self.minute_tracker))
		self.tick = self.tick + dt
		tick_rounded = math.floor(self.tick)
		gui.set_text(self.seconds, tostring(tick_rounded))
		--local pos = gui.get_position(self.seconds)
		--pos.x = pos.x + 5*dt
		--gui.set_position(self.seconds, pos)
		gui.set_enabled(self.zero, true)	
	end

Any suggestions please?

Use the Modulo operator, %. It gives you the remainder of a number after division by another number. This is the code I have for a “00:00” min:sec time display.

function update(self, dt)
	self.tick = self.tick + dt
	local seconds = self.tick % 60
	local minutes = (self.tick - seconds)/60 -- or = math.floor(self.tick/60)
	gui.set_text(textnode, string.format("%02d:%02d", minutes, seconds))
end

If you don’t know string.format(), look it up too. It’s very useful. In this case it’s converting “minutes” and “seconds” to integers padded with zeros to at least two characters, and adding a “:” between the two numbers. This way you only need one text node.

3 Likes

Thanks man!

1 Like