# How To Use table.sort On Table With Multiple Variables And Tables In It

I’m trying to make a table where I can put the name’s and racing times of players in a race. I want to sort them from least time to greatest time, and move around the players to be in order.

Basically, I want it to do this.

Before Sort:

``````local PlayerAssignments = {
Player1 = {Name = "FirstPlayer", Time = 10},
Player2 = {Name = "SecondPlayer", Time = 1}
Player3 = {Name = "ThirdPlayer", Time = 3},
Player4 = {Name = "ForthPlayer", Time = 7}
}
``````

After Sort:

``````local PlayerAssignments = {
Player2 = {Name = "SecondPlayer", Time = 1}
Player3 = {Name = "ThirdPlayer", Time = 3},
Player4 = {Name = "ForthPlayer", Time = 7}
Player1 = {Name = "FirstPlayer", Time = 10},
}
``````

Is there a way to use table.sort with this? I was able to use it on other tables, but since this one has a bunch of variables and tables, it’s confusing on how to do it. Also, let me know if you know of a better way of organizing the same stats in a table, I just thought of doing this to keep it tidy in one main table.

Thanks for the help!

The dictionary part of a table has no notion of order. If you make it an array of dictionaries as opposed to a dictionary of dictionaries you can get this to work.

``````local PlayerAssignments = {
{ Name = "SecondPlayer", Time = 1 },
{ Name = "ThirdPlayer", Time = 3 },
{ Name = "ForthPlayer", Time = 7 },
{ Name = "FirstPlayer", Time = 10 }
}

table.sort(PlayerAssignments, function(a, b)
return a.Time < b.Time
end)
``````
2 Likes

Oh I see, that makes sense. Thanks for the help! I’ll test it out later, and get back to you on how it works out.

EDIT: Quick question, is it typical to put spaces when constructing a table? I mean should it be:

1. {table}
or
2. { table }

Or is it more of a person-to-person habit? Such as declaring declaring variables like, “firstVariable = 1” vs. “FirstVariable = 1”?

Yes, just something I like to do.

1 Like

Ah okay, thanks. (30 char limit)

It worked! Thanks very much for helping me