table.sort抛出“无效的订单功能”

时间:2018-12-29 02:56:54

标签: sorting lua

我正在开发一个简单的朋友系统,并希望对其中的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)

当我添加几个朋友时它起作用。但是当我得到更多朋友时,它抛出异常“排序无效的排序功能”。 有人可以告诉我如何解决吗? :)

1 个答案:

答案 0 :(得分:1)

感谢@Paul Hebert和@Egor Skriptunoff,我知道了。

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

这意味着:

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

  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)
相关问题