Code: Select all
local teams = {'team1','team2','team3'}
local scores = {
team1 = 100,
team2 = 200,
team3 = 300
}
-- Returns a shallow copy of t so changes to basic values won't affect the original (see also deepcopy).
function table.copy(t)
local copy = {}
for k,v in pairs(t) do
copy[k] = v
end
return copy
end
-- returns a copy of teams sorted
local function SortTeamsByScore()
-- a local function inside a function for speed
local function HighestScore(teamA,teamB)
return scores[teamA] > scores[teamB]
end
local sortedTeams = table.copy(teams)
table.sort(sortedTeams, HighestScore)
return sortedTeams
end
This code may look complicated but the key to it is the built-in Lua function table.sort. This function takes an array and a comparison function and runs the comparison on pairs of values to determine which comes first. It is the fastest method, especially on large lists.
The table copy stuff is only relevant if you don't want to change the order in the original table - otherwise just sort teams 'in-place' for even more speed.
Method 2:
If you are only interested in the highest score there is an even faster way
Code: Select all
local teamScores = {
[100] = 'team1',
[300] = 'team2',
[200] = 'team3'
}
local scores = {100,300,200}
local highestScore = math.max(unpack(scores))
local bestTeam = teamScores[highestScore]
This works because math.max can take an unlimited number of arguments and unpack converts the table into arguments. It fails in the event of 2 teams having the same score.