Hello, I’m trying to make a bar similar to the one for stamina, but unlike this it decreases if you don’t eat, it is basically a hunger bar, well when adding a value for example 20 and if it is at 100, how do I only add the necessary amount without going over?
Example:

local Stamina = 95
local MaxStamina = 100
local SetStamina = function(Num)
Stamina += (Num/MaxStamina) * Stamina
end

Maybe use the math.clamp() function. It makes sure when a number is below a minimum, it will return the minimum number, if it goes over maximum number, it will return maximum number, if it is between the max and min, it will return that number.

Now I see why math.min (), but what I am looking for is that the function adds the stamina no matter what amount it is, for example suppose that the amount that it adds is a very large number, it is possible to reduce it and Just add what is necessary without going over Number 100?

local Amount = (Num/MaxStamina) * Stamina; -- However you calculate the amount to add here blah blah
Stamina = (Stamina + Amount) < MaxStamina and (Stamina + Amount) or MaxStamina; -- This will check to make sure that the stamina we are adding does not exceed our max stamina! If it does we simply set it to the max stamina!

Adding just what is necessary to fill it up would have no effect on the end goal and would therefore be rather pointless to calculate. If you for some reason needed to return the exact amount added (like xp carryover for a level up) then it would be worth doing, but for this case, since it just caps it without returning anything, I don’t think there is any merit. Any method for doing more would just add complexity for no change to the output.

the math.min thing set it to max if it exceeds it before assigning it to the variable. Though I should probably mention here that I was reading it from an addition only point of view, if you need it to handle negatives as well, you have to use math.clamp like others have suggested.

Just keep adding the value until it gets over the max value:

local minimum, maximum = 0, 100
local currentValue = 0
while currentValue < maximum do
currentValue = currentValue + 10 -- Adds 10 to the current value
currentValue = math.clamp(currentValue, minimum, maximum)
wait(1) -- Adds 10 every 1 second
end

This is just an example, you will need to change the code to fit your needs but this seems to be the basics of what you’re asking for

You would need to check if the sum of the current amount and the amount you already have, is less than the maximum amount.

If the sum is less, make it the stamina, otherwise set the stamina to the maximum.

local Stamina = 25
local MaxStamina = 100
local SetStamina = function(Amount)
local Sum = (Amount+Stamina)
local SumLessThanMax = ( Sum < MaxStamina)
if SumLessThanMax then
Stamina = Sum
else
Stamina = MaxStamina
end
end
SetStamina(55)
print(Stamina)