table排序
table.sort()
原型:table.sort (table [, comp])
解释:对⼀个长度为length=n的数组table排序,也就是对tab_table[1]到tab_table[n]排序,如果参数comp不省略,则它必须是⼀个函数,可以接收表tab_table的两个元素,并且在第⼀个元素⼩于第⼆个元素时返回true,其他情况返回false,如果省略参数comp,则Lua彼岸准运算符operator <;将会被使⽤。
local tabLanguage = {
"Lua",
"swift",
"python",
"java",
字符串长度排序
"c++",
};
print("\nLUA>>>>>>the source elements of table tabLanguage is:")
for k,v in pairs(tabLanguage) do
print(k,v)
end
-- 使⽤默认函数排序
table.sort(tabLanguage)
print("\nLUA>>>>>>After sort, the elements of table tabLanguage is:")
for k,v in pairs(tabLanguage) do
print(k,v)
end
-
- 定义⾃⼰的⽐较函数
local function my_comp(element1, elemnet2)
return string.len(element1) < string.len(elemnet2)
end
-- 使⽤⾃⼰的⽐较函数排序(按字符由短到长排序)
table.sort(tabLanguage, my_comp)
print("\nLUA>>>>>>After sort using my_comp, the elements of table tabLanguage is:")
for k,v in pairs(tabLanguage) do
print(k,v)
end
-- 再定义⼀个⾃⼰的⽐较函数
local function my_comp_new(element1, elemnet2)
return element1 > elemnet2
end
-- 使⽤⾃⼰的⽐较函数排序(按字符长段排序)
table.sort(tabLanguage, my_comp_new)
print("\nLUA>>>>>>After sort using my_comp_new, the elements of table tabLanguage is:")
for k,v in pairs(tabLanguage) do
print(k,v)
end
-- 定义处理nil的函数
local function my_comp_new_with_nil(element1, elemnet2)
if element1 == nil then
return false;
end
if elemnet2 == nil then
return true;
end
return element1 > elemnet2
end
-- 创造⼀个空洞
tabLanguage[2] = nil
-- 使⽤默认函数排序
-
-table.sort(tabLanguage, my_comp_new_with_nil)
print("\nLUA>>>>>>After sort using my_comp_new_with_nil, the elements of table tabLanguage is:")
for k,v in pairs(tabLanguage) do
print(k,v)
end
总结#
当我们省略了第⼆个参数comp时,排序函数使⽤了默认的排序⽅法,看起来是按字符的ANSII码从⼩到⼤排序的。
当使⽤我们⾃⼰定义的函数my_comp时,字符串是按其长度从短到长排序的。
当使⽤我们⾃⼰定义的函数my_comp_new时,字符串是按默认排序的反序排列的,那是因为我们在第⼀个元素⼤于第⼆个元素时返回了true,与定义恰恰相反,是不是很有意思。
当使⽤我们⾃⼰定义的函数my_comp_new_with_nil时,数组中的空值被踢掉了,要注意这种情况,在
函数my_comp_new_with_nil中要明确定义元素为nil的情况,否则程序是会直接报错的。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。