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(" LUA>>>>>>the source elements of table tabLanguage is:")

for k,v in pairs(tabLanguage) do

    print(k,v)

end

-- 使用默认函数排序

table.sort(tabLanguage)

print(" LUA>>>>>>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(" LUA>>>>>>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(" LUA>>>>>>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(" LUA>>>>>>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的情况,否则程序是会直接报错的。

原文地址:https://www.cnblogs.com/gd-luojialin/p/10962762.html