How to check which of the given numbervalues have the highest number?

Hi,

I have some numbervalues inside a player (they all in the same folder) and i want to check which one has the highest value. I think i need use for in pairs to get all numbervalues and then somehow check which one have the highest number. Maybe i need to place every numbervalue into table and then somehow find the highest value, but im not familiar with tables. Maybe anyone know how i can get the instace with highest value?

1 Like

You will need to use a for loop to go through every value. Outside of the for loop, you’ll need a variable that holds the current highest value. In the for loop you’ll have to use an if statement to check if the new number is greater than the current highest value variable. If the new value is higher then you need to replace the current highest value with the new value. At the end you should receive the highest number.

Here is an example:

local values = {1, 100, 3, 50, 69, 420, 1337, 1234}
local highest = nil

for _, value in pairs(values) do
	if not highest then
		highest = value
		continue
	end
	
	if value > highest then
		highest = value
	end
end

print(highest)
15 Likes

For this, you’d want to use table.sort:

local values = {}

for _,v in pairs(NumberValues:GetChildren()) do
    values[#values + 1] = {Obj = v; Value = v.Value}
end

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

local highestValuePair = values[1]
local highestObject = highestValuePair.Obj
local highestValue = highestValuePair.Value

Brief rundown: table.sort is a function used for sorting arrays in a given order. Given a function, table.sort will iterate over all matches and pass the two values of the match in the function. The function is expected to return true if you want the first value of the match to come before the second. After it goes through the function that I’ve given, the highest value will be the first entry of the table

4 Likes

You can do this, or you can do:

local highest = math.max(unpack(values))

This is really smaller as your method and no needs any loop.
Then this can cost less energy to running my script as your, as loops are really to use if you really need them, if you have a alternative then try to use the alternative. Hope this helps @ShkatulkaGames

20 Likes

And if I wanna get the lowest, would I just do math.min?

3 Likes

Exactly yes! It‘s better than using a loop

2 Likes