Reputation: 150
I'm developing a simple friend system and want to sort the friendData with some rules.
I compared two friends' status , level and offline-Time.
PS:A friend has 3 status.(Online = 3,Busy = 2,Offline = 1).
Here's my code.
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)
It works when I add several friends.But when I get more friends,It throws exception "invalid order function for sorting". Can someone please tell me how to fix it? :)
Upvotes: 4
Views: 1908
Reputation: 150
Thanks to @Paul Hebert and @Egor Skriptunoff ,I Figure it out.
The key is that compare(a,b) and compare(b,a) should have different returned results.
That means:
When iScore1 == iScore2,there should be an unique value for comparing(e.g.,accountID).
Different compared value should have different scores.
Here is the new code.
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)
Upvotes: 2