klaw Posted September 6, 2017 Share Posted September 6, 2017 I have a table: local myTable = { [204] = { 50, 10 }, [820] = { 22, 32 }, [103] = { 42, 66 }, } How can I sort this table by the first index, so it'd be in order, like: 50, 42, 22 descending. Link to comment
Administrators Lpsd Posted September 7, 2017 Administrators Share Posted September 7, 2017 table.sort(myTable, function(a, b) return a[1] > b[1] end) I think... Link to comment
Moderators IIYAMA Posted September 7, 2017 Moderators Share Posted September 7, 2017 (edited) You can't order this table since it is already ordered. local myTable = { [204] = { 50, 10 }, [820] = { 22, 32 }, [103] = { 42, 66 }, } Will look like this: local myTable = { [103] = { 42, 66 }, [204] = { 50, 10 }, [820] = { 22, 32 }, } If you want to order this table, you need a different format were there are no custom indexes. Edited September 7, 2017 by IIYAMA Link to comment
Tails Posted September 8, 2017 Share Posted September 8, 2017 (edited) You don't have to change your table format (at least it depends on what you're doing and how your script is functioning). Check this old post of mine for an easy solution: Edited September 8, 2017 by Tails Link to comment
Moderators IIYAMA Posted September 8, 2017 Moderators Share Posted September 8, 2017 lol, you are changing the table format of the copy. Then you can better use two linked tables, saves you a lot of performance. Link to comment
Tails Posted September 8, 2017 Share Posted September 8, 2017 (edited) 2 hours ago, IIYAMA said: lol, you are changing the table format of the copy. Then you can better use two linked tables, saves you a lot of performance. This is a perfectly normal way of doing it. Sometimes you want to take some data from an existing table into a new one and use that for sorting without messing with the original. But go ahead and post your solution here, OP needs it. Edited September 8, 2017 by Tails Link to comment
Moderators IIYAMA Posted September 8, 2017 Moderators Share Posted September 8, 2017 local myTable = { {103, 42, 66 }, {204, 50, 10 }, {820, 22, 32 } } local myTableNewFormat = { --[[ [103] = {103, 42, 66 }, -- shared/linked with myTable [204] = {204, 50, 10 }, [820] = {820, 22, 32 } ]] } for i=1,#myTable do myTableNewFormat[myTable[i][1]] = myTable[i] end As you know tables are objects and they can exist at multiple places at the same time. Which means that myTable and myTableNewFormat contains exactly the same data, but with different indexes. 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