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.

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I asked for. Thank you very much, it solved the problem beautifully!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.