Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you compare number values?

I have multiple NumberValues stored in the replicated storage and I want to find out which one is the largest without using the ">" and "<" signs since there is too much values to compare. Is there a way to do it without the signs.

I have tried by putting them all in a table and using table.sort, but I got an error saying "cannot compare userdata"

1 comment

0

You could try doing them all two at a time and just keeping the greatest value each time.  Use :GetChildren and if the value is greater than the previous winner then set it as the new winner and move to the next value

2 answers

✓ Accepted answer

Simply loop over all values and store the highest one.

Here's an example.

function GetHighestValue(Stuff)
	local Number,Inst = 0,nil -- create values
	for _,v in pairs (Stuff) do -- loop over values
		if v:IsA("NumberValue") and v.Value > Number then -- Check if its larger than any previous checks
			Number = v.Value
			Inst = v
		end
	end
	return Number, Inst -- Return the values
end

local HighestNumber,NumberValue = GetHighestValue(workspace.Folder:GetChildren())

4 comments

0

Can you explain why is there 2 local variables, HighestNumber and NumberValue?

0

The function is written to return two values to whatever it's called upon. You can split them up into two different variables accordingly, you've now got access to two different data types at your grasp, calculated by a single function

0

I wasnt sure if you needed the instance or the highest value, so i made the function return both. If you want to learn more about this, check the roblox wiki for 'Function return'

0

Thank you so much!

You're essentially searching for the same result that this similar code produces for finding a maximum value:

local function findMax(array)
	local max = array[1]
	for i = 2, #array do
		if (array[i] > max) then
			max = array[i]
		end
	end
	return max
end

print( findMax {5, 10, 15} ) --> 15

You would just apply this to your number value objects. The logic stays the same; you just have to modify the code to fit your specific case. Example:

local function findMax(array)
	local max = array[1].Value
	for i = 2, #array do
		if (obj[i].Value > max) then
			max = obj[i].Value
		end
	end
	return max
end

print( findMax {IntValue, IntValue, IntValue} ) -- > largest IntValue value

If you want to find the reference to the actual number value object that contains the "max number," then you could just change the max variable to represent array[1] instead of array[1].Value and reassign new max values to the object instead of the object's value.

This discussion is preserved as it was. New answers, comments, and votes are closed.