Jump to content

Sort Table Problem


Overkillz

Recommended Posts

Hello dear community. Im having a simple issue which is annoying me a lot ...

Well, Im trying to sort a table like the following one by Player points. However, it doesn't return the ordered from high to lower. It doesn't even order it.

simpleTable = {
		player1 = {points = 25, playerName = "RandomNick1"},
		player2 = {points = 1, playerName = "RandomNick2"},
		player3 = {points = 13, playerName = "RandomNick3"},
		player4 = {points = 27, playerName = "RandomNick4"},
		player5 = {points = 7, playerName = "RandomNick5"}
}
	
table.sort (simpleTable, function (a, b) return a.points > b.points end) 

I hope u can bring me a hand with my problem or another way to fix it.

Thanks for reading. Regards.

Link to comment
  • Moderators

It can't be sorted because the indexes of the array are strings.

 

The indexes are now:

"player1", "player2", "player3", "player4", "player5"

Because:

{
	player1 = {points = 25, playerName = "RandomNick1"}
}
-- is them same as
{
	["player1"] = {points = 25, playerName = "RandomNick1"}
}

 

Before you can sort them , you need the indexes to be the ones of an array:

1, 2, 3, 4, 5

 


So you need to transform the keys from one form to another.

simpleTable = {
		player1 = {points = 25, playerName = "RandomNick1"}, -- < item
		player2 = {points = 1, playerName = "RandomNick2"},
		player3 = {points = 13, playerName = "RandomNick3"},
		player4 = {points = 27, playerName = "RandomNick4"},
		player5 = {points = 7, playerName = "RandomNick5"}
}

-- Make a new empty table.
newSimpleTable = {}

-- Use the pairs loop. (not the ipairs loop, because that one can't read the items with custom keys)
for key, data in pairs(simpleTable) do
	-- Insert all items into the new table.
	newSimpleTable[#newSimpleTable + 1] = data
end

-- Now you can sort them.
table.sort (newSimpleTable, function (a, b) return a.points > b.points end) 

 

 

 

 

 

 

Edited by IIYAMA
  • Like 2
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...