Lua: Sort String array with varying casing
Asked Answered
Z

1

7

I'm facing an issue with Lua while using the table.sort function. I wrote a little snippet ready for you to test, if you want to convince yourselves.

test = {"apple", "Bee", "clown" }
table.sort( test )

for k, v in pairs( test ) do
    print( k, v )
end

The result is

1   Bee
2   apple
3   clown

even though my desired result would look like this

1   apple
2   Bee
3   clown

I already managed to figure out that this is because the table.sort function uses the default "<" operator, and "B" has an ASCII-value of 66, which is obviously lower than the ASCII value of "a" or "c", which are 97 and 99 respectively. I know that I'm able to apply a custom function when calling table.sort, but I have no clue how that function would look like.

Also, it is not an option to make all letters lower- or uppercase, unless you'd be able to restore them later.

Any help is greatly appreciated.

Zellers answered 10/1, 2018 at 13:39 Comment(0)
B
14

The function table.sort accepts a function as second parameter to test your values.

Example

table.sort(tTable, function(a, b) return a:upper() < b:upper() end)
Blalock answered 10/1, 2018 at 14:11 Comment(1)
That's exactly what I asked for. Thank you very much, it solved the problem beautifully!Zellers

© 2022 - 2024 — McMap. All rights reserved.