Jump to content

How get a max value in table


Recommended Posts

  • Administrators

Something like this should do

function getMaxValue(table)
	local max_val, key = 0, 0
	for i,v in pairs(table) do
		if v > max_val then
			max_val, key = v, i
		end
	end
	return max_val, key
 end

 

Then use:

value, key = getMaxValue(exampleTable[player].kill)

 

 

Edited by LopSided_
  • Like 1
Link to comment

or you can simply sort the table from biggest to smallest by;

table.sort(table, function(a,b) return a.kill > b.kill end)

 and then, when you have the highest value on the top of the sorted table, You simply get the first row in this table and it will be the biggest.

  • Like 1
Link to comment
  • Administrators
32 minutes ago, SuperCroz said:

or you can simply sort the table from biggest to smallest by;


table.sort(table, function(a,b) return a.kill > b.kill end)

 and then, when you have the highest value on the top of the sorted table, You simply get the first row in this table and it will be the biggest.

Won't this lose the key from the original table? 

Although saying that, my example assumes numerical key/indexes.

Edited by LopSided_
Link to comment
11 minutes ago, LopSided_ said:

Won't this lose the key from the original table? 

Although saying that, my example assumes numerical key/indexes.

the key isn't important since we got the value.

Besides, I gave another example because I couldn't understand yours.

max_val = 0, 'if v > max_val then' which means 'if v > 0 then' we have the max_val? I would like to know more how this works, If possible.

Link to comment

I hope this is what the OP is looking for :)

function getTopScores()
	local scores = {}
	for plr, v in pairs(exampleTable) do
		table.insert(scores, {name = getPlayerName(plr), kills = v.kills}
	end
	table.sort(scores, function(a, b) return a.kill > b.kill end)
	return scores
end

local scores = getTopScores()
outputChatBox("Top scorer is "..scores[1].name.." with "..scores[1].kills.." kills!") 

It creates a list with the names and kills of each player in your table then sorts it by the kills.

Then you can output the first one in the list or all of them put them in a grid list or something.

36 minutes ago, LopSided_ said:

Won't this lose the key from the original table? 

To avoid that you should just create a new table.

Hope this helps everyone :)

  • Like 3
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...