Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How does table.sort work?

Asked by 8 years ago

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

Log in to vote
4
Answered by
Pyrondon 2089 Game Jam Winner Moderation Voter Community Moderator
8 years ago

(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.

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. XAXA 1569 — 8y
Ad

Answer this question