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的情況,否則程序是會直接報錯的。