Lua:使用不同大小写的Sort String数组 [英] Lua: Sort String array with varying casing

查看:116
本文介绍了Lua:使用不同大小写的Sort String数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 table.sort 函数时,我遇到了Lua的问题.如果您想说服自己,我写了一段代码供您测试.

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

结果是

1   Bee
2   apple
3   clown

即使我想要的结果看起来像这样

even though my desired result would look like this

1   apple
2   Bee
3   clown

我已经设法弄清楚这是因为 table.sort 函数使用默认的<"运算符,"B"的ASCII值为66,明显低于"a"或"c"的ASCII值,分别为97和99.我知道我可以在调用 table.sort 时应用自定义函数,但是我不知道该函数的外观.

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.

非常感谢您的帮助.

推荐答案

函数 table.sort 接受一个函数作为第二个参数来测试您的值.

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

示例

table.sort(tTable, function(a, b) return a:upper() < b:upper() end)

这篇关于Lua:使用不同大小写的Sort String数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆