Overkillz Posted January 3, 2018 Share Posted January 3, 2018 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 IIYAMA Posted January 3, 2018 Moderators Share Posted January 3, 2018 (edited) 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 January 3, 2018 by IIYAMA 2 Link to comment
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now