table.sort 抛出 "invalid order function"

我正在开发一个简单的好友系统,希望能按照一些规则对 friendData 进行排序。

我比较了两个好友的状态、等级和离线时间。

PS:一个好友有3个状态。(在线=3,忙碌=2,离线=1)

以下是我的代码。

local function compare(friend1,friend2)
    local iScore1 = 0
    local iScore2 = 0
    if friend1["eStatus"] > friend2["eStatus"] then
        iScore1 = iScore1 + 1
    end
    if friend1["iLevel"] > friend2["iLevel"] then
        iScore1 = iScore1 + 1
    end
    if friend1["iOfflineTime"] < friend2["iOfflineTime"] then
        iScore1 = iScore1 + 1
    end
    return iScore1 > iScore2
end
table.sort(FriendData,compare)

当我添加几个朋友时,它可以工作。但是当我有更多的朋友时,它抛出了异常 "invalid order function for sorting"。 有人能告诉我如何修复它吗? :)

点赞
用户10845029
用户10845029

感谢 @Paul Hebert 和 @Egor Skriptunoff ,我终于搞明白了。

关键在于 compare(a,b) 和 compare(b,a) 应该返回不同的结果。

具体而言:

  1. 当 iScore1 == iScore2 时,应该用一个唯一的值进行比较(例如 accountID)。

  2. 不同的比较值应该有不同的分数。

下面是新代码。

local function compare(friend1,friend2)
    local iScore1 = 0
    local iScore2 = 0
    if friend1["eStatus"] > friend2["eStatus"] then
        iScore1 = iScore1 + 100
    elseif friend1["eStatus"] < friend2["eStatus"] then
        iScore2 = iScore2 + 100
    end
    if friend1["iLevel"] > friend2["iLevel"] then
        iScore1 = iScore1 + 10
    elseif friend1["iLevel"] < friend2["iLevel"] then
        iScore2 = iScore2 + 10
    end
    if friend1["iOfflineTime"] < friend2["iOfflineTime"] then
        iScore1 = iScore1 + 1
    elseif friend1["iOfflineTime"] > friend2["iOfflineTime"] then
        iScore2 = iScore2 + 1
    end
    if iScore1 == iScore2 then --它们都是0。
        return  friend1["accountID"] > friend2["accountID"]
    end
    return iScore1 > iScore2
end
table.sort(FriendData,compare)
2018-12-29 05:36:36