Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: Sort String array with varying casing

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.

like image 637
Legofan431 Avatar asked Jan 10 '18 13:01

Legofan431


1 Answers

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)
like image 86
Phisn Avatar answered Nov 15 '22 06:11

Phisn