Need help understanding this function

I think I’m doing my maths wrong because for example lets say my I have 22 as my argument. I want to find seconds. In the first variable of function convertToHMS, I convert it into minutes and this is my process. (22 - 16) / 60 = 6/60 = 0.1. On the next line of code I do seconds = 22 - 0.1*60 = 22-6 = 16, so should seconds = 16??? but what I inputed for seconds was 22? Also the output is 22 so that means my math is wrong

local function format(int)
	return string.format("%2i", int)
end

local function convertToHMS(seconds)
	local Minutes = (seconds - seconds%60)/60
	seconds = seconds - Minutes*60
	print(seconds)
	local Hours = (Minutes - Minutes%60)/60 
	Minutes = Minutes - Hours*60
	return format(Minutes)..":"..format(seconds)
end

print(convertToHMS(22))

2 Likes

The steps of the function would be:
Minutes = (22 - 22)/60 = 0
seconds = 22 - 0*60 = 22
print(22)
local Hours = (0 - 0)/60 = 0
return 0:22

And so it returns “0:22” which is what you would expect, as giving it 22 seconds should give you 0 minutes and 22 seconds.

In your process you seemed to put (22 - 16) / 60 = 6/60 = 0.1 for the minutes line, however 22%60 is 22, not 16, and so minutes just becomes 0. And then this would fix the rest of your maths as the seconds line becomes 22 - 0*60 = 22. So perhaps your confusion is coming from the modulus operator?

1 Like

hi thanks for replying, i was stuck on this the whole day, how would you calculate modules operator because I thought that this had somthing to do with division and the remainder was the outcome

1 Like

i fixed it I just needed a brush up on long division

1 Like

Yeah that’s pretty much how modulus works, the modulus operator will give you the remainder of a number when its divided by some number. So if we have x % y = z, then z will be the remainder of x/y. Some examples might be helpful:
15 % 7 = 1 as 15/7 = 2 with a remainder of 1
20 % 5 = 0 as 20/5 = 4 and there are no remainders
19 % 2 = 1 as 19/2 = 9 with a remainder of 1
When the first number is less than the second (dividend is less than the divisor) then the modulus operator will just give you the first number back (the dividend), ie
3 % 5 = 3
10 % 100 = 10
22 % 60 = 22

Hope that helps.

1 Like