表格排序抛出“无效的排序函数”错误。

4

我正在开发一个简单的好友系统,并希望通过一些规则对好友数据进行排序。

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

PS:一个好友有三种状态(在线=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)

当我添加几个朋友时,它可以正常工作。但是当我的朋友数量增加时,它会抛出异常“无效的排序函数顺序”。 有人能告诉我如何修复它吗?:)


1
如果iScore1 = iScore2会发生什么?如果这些值中有任何一个相同,会怎样? - Paul Hebert
如果 iScore1 == iScore2,我期望该函数返回 false。 - 47 kk
看看这个:https://dev59.com/nJbfa4cB1Zd3GeqPzdZF - Paul Hebert
排序函数无效,因为compare(friend1, friend2)compare(friend2, friend1)都有可能返回true - Egor Skriptunoff
确实。谢谢帮忙。:) - 47 kk
1个回答

2
感谢@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 --They are both 0.
        return  friend1["accountID"] > friend2["accountID"]
    end
    return iScore1 > iScore2
end
table.sort(FriendData,compare)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接