How to sort table of objects?

Hello!

I have an array (_G.Sessions) and each 5 seconds I would like to sort it. Here’s the object:

-- Session object 1
{
     host = "player1",
     StartTime = {
         Str = "19:30"
         Hour= 19
         Min= 30
     }
}

Now if I have another object:

-- Session object
{
     host = "player1",
     StartTime = {
         Str = "19:00"
         Hour= 19
         Min= 0
     }
}

And I’d have them inserted into _G.Sessions, how can I sort them to go from earliest to latest starting time? Thanks in advance for your assistance! :pray:

1 Like

table.sort(t, func) accepts a table to be sorted t and an optional comparison function to use in the sorting process. It replaces the less-than < operator. So, in your case:

local function compareStartTimes(lhs, rhs)
   local lhsTime = lhs.StartTime.Min + lhs.StartTime.Hour * 60
   local rhsTime = rhs.StartTime.Min + rhs.StartTime.Hour * 60
   return lhsTime < rhsTime
end
table.sort(_G.Sessions, compareStartTimes)

Although this should solve your problem, there’s a number of things that smell wrong with your approach.

  • You probably want to insert your data in a sorted fashion instead of sorting it on a regular time interval.
  • Instead of saving hours and minutes (and likely counting both), you should just save the total number of seconds. When it comes time to display hours and minutes as a string, it is far more trivial to determine hours/minutes from that second counts, rather than bend over backwards trying to work with separate unit values.
  • Using _G like this is prone to race conditions, unless you have some mechanic in place to guarantee that whatever you put in _G is guaranteed to be there (a busy-wait loop is not a good solution!)
    • You probably want to require a ModuleScript, even if that ModuleScript’s only purpose is to return a blank table to be used as your array, ie. require(someModuleScript) and that ModuleScript contains only return {}, for instance.
2 Likes

Hello! Thank you very much for taking time out of your day to help me! :slight_smile:

I was just about to post that I managed doing it using the following table.sort:

table.sort(_G.Sessions,
			function(a,b)
				return not(a.StartTime.Hour > b.StartTime.Hour or (a.StartTime.Hour == b.StartTime.Hour and a.StartTime.Min > b.StartTime.Min))
			end
		)

It’s not that fancy as it should be, though. I like your approach of doing *60 more :smiley:

As we are on a very tight deadline we plan on making everything “work”, and optimizing it in the coming month. I will for sure check your feedback again very soon! Thanks again!!