gpt4 book ai didi

sorting - table.sort 抛出 "invalid order function"

转载 作者:行者123 更新时间:2023-12-02 12:08:58 26 4
gpt4 key购买 nike

我正在开发一个简单的好友系统,想要对friendData进行一些排序规则。

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

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)

当我添加几个 friend 时它可以工作。但是当我有更多 friend 时,它会抛出异常“排序功能无效”。有人可以告诉我如何修复它吗? :)

最佳答案

感谢@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)

关于sorting - table.sort 抛出 "invalid order function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53966329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com