0

Is it possible to sort somehow table by table indexes name?

Table = {
   ["1. Xm1014"] = {},
   ["2. M3"] = {},
   ["3. M4A1"] = {}
}

and so on, it show me such thing in ending: https://i.stack.imgur.com/LoPwx.png

Is kinda mess but idk how can i sort'em with names.

Mora Rus
  • 1
  • 1
  • have you tried `table.sort`? – DarkWiiPlayer Mar 08 '20 at 08:38
  • Does this answer your question? [Sorting a Lua table by key](https://stackoverflow.com/questions/26160327/sorting-a-lua-table-by-key) – luther Mar 08 '20 at 08:53
  • Yes i tried. I also tried this thingy: table.sort(Table, function(a, b) return (a:match("%d%. ") or a) < (b:match("%d%. ") or b) end) – Mora Rus Mar 08 '20 at 08:56
  • There are many duplicates of this question. In short, Lua tables do not preserve their index order, so there's no way to sort your table without changing it into some kind of array. – luther Mar 08 '20 at 08:56
  • The problem is that i couldn't use indexing of table such as this one: `[1] = ["1. White"] = {}, [2] = ["2. Red"] = {} etc` I made special auto-menu for my code that finding Indexes as keynames and also buttons. Everything is working nice except this sort.. Well okay since is not possible to sort it i gonna try smth another. Thanks – Mora Rus Mar 08 '20 at 08:59
  • Mora, why is it important to have the `1.` or the `2.` and on? If you want to preserve their order, store it as an index, then you can iterate through the table and return the `index` and `value` as a string (e.g. `for i,v in ipairs(Table) do print(i .. ". " .. v) end`? That would produce the order that you are searching for. So, is there a reason you cannot do that? – Josh Mar 08 '20 at 12:41
  • Yeah, there's a reason. I'm storing index name as a title and is also value, it turnin' into menu button as first, then it became name of the title: 1) The order numeration as it should be like: https://i.imgur.com/OldDYjK.png 2) The menu buttons(also mess there): https://i.imgur.com/Mwx1EFU.png 3) The difference between 1-st screen and how is in real: https://i.imgur.com/i4c2oPC.png ____ By the way there is difference between **ipairs** and **pairs** in that case? I thought ipairs wouldn't continue if see a missing i+1, moreover my index is a string so it lead to nothing. – Mora Rus Mar 08 '20 at 15:32
  • Well i have re-done my all things under that index u suggested me. I've changed everything and now is even working better and as i wanted. thank u @Josh and others. – Mora Rus Mar 08 '20 at 17:34

0 Answers0