Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How does table.sort work?

So, I've read the wiki article/stub on table.sort, but it's unclear to me about how it actually gets sorted. Also, how does it sort strings vs numbers?

If anyone who is knowledgeable with table manipulation could explain it a bit more than the wiki does, I'd really appreciate it. Thanks! :)

1 answer

✓ Accepted answer

(I know I already answered this in the chat, but might as well put it here in case someone else needs it)

I'm not 100% on this, but it seems like table.sort sorts items in a table alphabetically, but separates the uppercase and lowercase. So, if you had all uppercase (or all lowercase), it would sort them alphabetically:

tab = {C, B, D, A}
table.sort(tab)
print(table.concat(tab, " "))

Would print: A B C D, whereas if you had a mixture of uppercase and lowercase strings, it would sort the uppercase ones, and then the lowercase would come after:

tab = {C, b, D, a, T}
table.sort(tab)
print(table.concat(tab, " "))

This would print: C D T a b.

As for numbers (and again, this is from brief testing, so if this is incorrect, someone please correct me), it seems to sort them in ascending order:

tab = {100, 2, 53, 8, 92, 205}
table.sort(tab)
print(table.concat(tab, " "))

Should print: 2 8 53 92 100 205. If it's a mixed table, or there's a boolean or an object in the table, it will throw an error.

Hope this helped.

1 comment

2

There's an optional second argument for table.sort, which is a callback function that compares two elements of a table and returns true if the first element is less than the second.

This discussion is preserved as it was. New answers, comments, and votes are closed.