Sorting tables values from least to most

Hello!

I have stumbled into this problem where I am trying to sort my table. I am creating a racing game, and at the end I am trying to figure out how to organize the table from least to most (in order to create a leaderboard that shows the best times to the worst).

here’s what my table looks like

local playerTime = {['PlayerName1'] =25 , ['PlayerName2'] = 50, ['PlayerName3'] = 40}

I’ve tried looking into table.sort() but revived a lot of “attempt to call a nil value” in the output.

Any feedback would be appreciated!

1 Like

try adding all the number values associated with each index into another table and use a sort algorithm

1 Like

There’s an awesome reply that wonderfully explains how to use table.sort(). But, I’ll do a quick demo here!

So, I shuffled the table you had, just to show how it works:

local playerTime = {['PlayerName3'] = 50, ['PlayerName1'] = 25 , ['PlayerName2'] = 40,}
table.sort(Table, Function) --table = playerTime, function = how to sort the table

By default, the function is like this (least to greatest):

local function sort(a, b)
	
	if a < b then --the system takes two values at the time and compares them
		
		return true --if a < b, then it returns true and puts "a" before "b"
		
	end
	
end

Even though you don’t need this, this is the greatest to least function (the other way around):

local function sort(a, b)
	
	if a > b then 
		
		return true --if a > b, then it returns true and puts "a" before "b"
		
	end
	
end

Now let’s put this into action:

table.sort(playerTime) --no function needed because default is least to greatest

print(playerTime["PlayerName1"], playerTime["PlayerName2"], playerTime["PlayerName3"])
--output: 25, 40, 50 (it worked!)

I didn’t get any errors this way.

Hope that helps!

8 Likes

@kingerman88

another idea,
add the values to a table and use my module here :

and use this script :



  local module = require(game.ServerScriptService.Sort)
  local playerTime = {


  ['PlayerName1'] = 25 ,
  ['PlayerName2'] = 50 ,
  ['PlayerName3'] = 40 ,
                   }

  local values = {}

  for k,v in  pairs(playerTime)  do
      table.insert(values, v)
  end
 
 
  print( module.quicksort(values, true)) --> prints in ascending order

  -- false for descending

try editing the code in the module or the script to fit your needs, for instance if you would require the index after sorting.

It only accepts numerical arrays.

@TheCarbyneUniverse 's way is the right and simpler way to do it

1 Like