How would you sort a table of Objects containing strings lexicographically?

For example, I have a table,

local Strings = {{str = "abcc"}, {str = "abc"}, {str = "potato"}, {str = "dog"}}

And I need them sorted to be lexicographical.

{{str = "abc"}, {str = "abcc"}, {str = "dog"}, {str = "potato"}}

I need to use table.sort, but in Rbx.Lua, there lacks a compareTo for strings (compared to Java).
How can I accomplish this?

1 Like

How to Sort Dictionaries Complex Arrays:

There’s a second argument in table.sort():

table.sort(array t, function comp = nil)

In this case:

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

Of course you can use this for sorting:

  • Alphabetical
  • Numerical
  • etc. (too lazy to add up or I’m just unable to think of any)

Further information: https://www.lua.org/pil/19.3.html
Source topic: Behavior of the Explorer's sort, and table.sort()
Required knowledge: https://en.wikipedia.org/wiki/Lexicographical_order

6 Likes

I never knew you could use comparison operators to compare strings lexicographically. Is there a reference in the Lua handbook that shows this information?

Edit: found it
https://www.lua.org/pil/3.2.html

1 Like