Sorting a table

So a while ago I found a dev forum reply that answers the topic but I cant find it.

My problem is that I have a table like this:

[10] = "dsad";
[100] = "dsad";
[1000] = "dsad";

But when I use a for loop and print it it isnt in order and I need to sort it.

I know I use table.sort() and use the seconds parameter, but I forgot how to.

What do you mean exactly by sorting it?
Numerically? Alphabetically?

Numerically, 10, 100, 1000.

When I print it it isnt in order like that

If your table is structured like so, you could look into using custom iterators, or if they are not in a way that make sense (i.e not 10,100,1000 but instead 10,16,515) you can use any sorting algorithm but instead sort the keys (Yet I am not entirely sure after doing so will allow you to loop through the table numerically)
One sure way to do this will be to create a new table that contains the keys of the said table (that is sorted with table.sort, and loop through the newly created table while indexing values with oldtable[v] from for _, v in ipairs(newtable).

Unfortunately, you can not sort associate tables in Lua. You have to add in tables inside the main table like so:

local tbl = {
    {1000, "dsad"};
    {10, "dsad"};
    {100, "dsad"};
}

And then sort it using table.sort(), like so:

table.sort(tbl, function(a, b)
   return a[1] < b[1] 
end)
Code I used to test
local tbl = {
    {1000, "dsad"};
    {10, "dsad"};
    {100, "dsad"};
}

table.sort(tbl, function(a, b)
   return a[1] < b[1] 
end)

for _,v in ipairs(tbl) do
    print(v[1], v[2])
end
2 Likes