table.sort()

类型 函数
table.*
返回值
修订 版本 2024.3703
关键词 表,数组

概述

对表元素进行原地排序,排序顺序由给定参数决定,排序范围从 table[1]table[n],其中 n 为表的长度。它接收要排序的表(数组)以及一个可选的 compare 比较函数。此 compare 函数接收两个参数,如果第一个参数应该排在排序数组的前面,则必须返回 true。如果**未**给出 compare 函数,则使用标准 Lua 运算符 <

排序算法并非完全稳定;也就是说,被给定顺序视为相等的元素,它们的相对位置可能会因排序而改变。

语法

table.sort( array [, compare] )
数组 (必填)

数组. 要排序的数组。

比较函数 (可选)

函数. 如果未给出,则使用标准 Lua 运算符 <

示例

从小到大
local t = { 3,2,5,1,4 }

local function compare( a, b )
    return a < b  -- Note "<" as the operator
end

table.sort( t, compare )
print( table.concat( t, ", " ) )  --> 1, 2, 3, 4, 5
从大到小
local t = { 3,2,5,1,4 }

local function compare( a, b )
    return a > b  -- Note ">" as the operator
end

table.sort( t, compare )
print( table.concat( t, ", " ) )  --> 5, 4, 3, 2, 1
字母顺序(子表)
local fruitList = {
    { fruitName="apple", fruitColor="red" },
    { fruitName="watermelon", fruitColor="green" },
    { fruitName="orange", fruitColor="orange" },
    { fruitName="lemon", fruitColor="yellow" }
}

local function compare( a, b )
    return a.fruitName < b.fruitName
end

table.sort( fruitList, compare )

for i,v in ipairs( fruitList ) do
    print( i, v.fruitName )
    --> 1   apple
    --> 2   lemon
    --> 3   orange
    --> 4   watermelon
end