Legofan431
Legofan431

Reputation: 173

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.

Upvotes: 7

Views: 6229

Answers (1)

Phisn
Phisn

Reputation: 881

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)

Upvotes: 14

Related Questions