How would you sort a table in Alphabetical Order?

I have a table which I use for a grid system but I need it in order.
The Number digit has no relevance as I’m 90% sure that it will always be the same in each table

I just want to write a function so that I can sort these tables whenever they can potentially be out of order

I have tried to learn table.sort but the Wiki doesn’t really go into enough detail, so if there’s a post that explains it better that would be highly appreciated

Table = {
	"A:1",
	"B:1",
	"C:1",
	"D:1"
}
3 Likes

table.sort requires you to give 2 things, a table to sort, and a function to used to determine the sorting used, where if it returns true, it means the first element must come before the second by default, it uses <. Which would look like this

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

Which does an ascending order sort. If it was >, it would’ve done a descending order. My guess for how it works for strings is that it converts the string to ASCII decimals/numbers and then compares that number when sorting. This would also explain why in some cases capital letters are in places you wouldn’t expect them to be if you ever test that. Example

local tbl = {"B", "a", "g", "e"}

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

for i,v in pairs(tbl) do
    print(v) 
end

The result would give

B
a
e
g

Because in Ascii, the decimal of capital letters is smaller than lower case letters (B is 66 and b is 98).

But to answer your question, if you just do table.sort(Table), it should be enough for your usecase if you only use Capitals or lowercase. Or if you’re planning on using before, use a custom function that compares the lower case values via :lower() as @Nodehayn stated, which sorry that I didn’t mention it at first, it’s late at nigh there

Please ask if you have more questions about table.sort as I may’ve forgot to mention something

26 Likes

You can actually just call :lower() or string.lower() on the variable (a) and (b) to compare them with their ASCII values. I tested it myself and it worked.

table.sort(tbl, function(a,b)
	return a:lower() < b:lower()
end)

for i,v in pairs(tbl) do
	print(v)
end

Output: a, B, c

12 Likes

Yep, works perfectly thanks for the help.

1 Like