Help making code more efficient

Hello.

I spent a an hour or two working on this function that converts a high amount of seconds (i.e. 2,000,000) to, depending on how many seconds it is, minutes, hours, days, months, and/or years.

Here is what I have as of now:

function module.SortSeconds(total)
	-- vals
	local values = {}

	values[1] = {"Year",0}
	local years = values[1]
	values[2] = {"Month",0}
	local months = values[2]
	values[3] = {"Week",0}
	local weeks = values[3]
	values[4] = {"Day",0}
	local days = values[4]
	values[5] = {"Hour",0}
	local hours = values[5]
	values[6] = {"Minute",0}
	local minutes = values[6]
	values[7] = {"Second",0}
	local seconds = values[7]

	seconds[2] = total

	if total > 157680000 then -- I added this because it kept crashing with higher amounts of seconds.
		seconds[2] = 0
		years[2] = 5
	end

	-- the stuffs
	while true do
		if seconds[2] >= 60 then
			minutes[2] += 1
			seconds[2] -= 60
		elseif minutes[2] >= 60 then
			hours[2] += 1
			minutes[2] -= 60
		elseif hours[2] >= 24 then
			days[2] += 1
			hours[2] -= 24
		elseif days[2] >= 31 then
			months[2] += 1
			days[2] -= 31
		elseif months[2] >= 12 then
			years[2] += 1
			months[2] -= 12
		else
			break
		end
	end
	return values
end

Any help is appreciated.

Thanks,
Ham

You’d be better off moving this to the Code Review section for help with this.

Sorry, I don’t use the devforum often.

Thats ok, dont give me the solution, just change its category.

I also clicked scripting support. No idea why it went here lol.

You can still change it. . . .

Oh, I already did that. Thanks for the suggestion though.

1 Like

Your function works but it’s very inefficient.
I wouldn’t use a loop for such things; here’s how I do it.

function GetDate:Remaining(st)
	if st > 0 then
		local t = math.floor(st)
		local m = math.floor(t / 2629743.83)
		t = t - m * 2629743.83
		local w = math.floor(t / 604800)
		t = t - w * 604800
		local d = math.floor(t / 86400)
		t = t - d * 86400
		local h = math.floor(t / 3600)
		t = t - h * 3600
		local mi = math.floor(t / 60)
		t = t - mi * 60
		local date = {
			m = m,
			w = w,
			d = d,
			h = h,
			mi = mi,
			se = math.floor(t)
		}	
		return date
	end
	return "Expired"
end

Calling this function with a positive value of seconds will return a table with it’s values.

local info = GetDate:Remaining(60) --60 seconds
print(info)

Kinda just looks like you copied it from else where…Nevertheless, thanks. I’ll tweak it to work for my situation.

If you don’t want help don’t ask :slight_smile:

3 Likes

wow i felt that into my soul right now xD