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

How would you make Precentage chance of something happening?

Hello, I'm just not sure how you could do precentage chance which means for example 15% chance of getting an item. I found an way to do it, but I'm sure there are better ways to do this. The code I found:

local chance = 15
if math.random(1,100) < chance then
--Give item
else
--Do not give item
end

Thanks for All Answers and Excuse me my poor English.

1 comment

1

This is the most effective way... and the simplest. The % Sign returns some number if it is possible to multiply it by a whole number to get that number...

1 answer

✓ Accepted answer

The only way to produce "randomness" in Lua is math.random. math.random can be used in three ways (all which produce completely uniform results):

  • math.random(low, high) produces a random integer between low and high (inclusive)
  • math.random(high) produces a random integer between 1 and high (inclusive)
  • math.random() produces a random real between 0 and 1 (including 0 but not including 1)

Thus, all of the following have a 15% chance of being true

math.random() < 0.15
math.random(1, 100) <= 15
math.random(100) <= 15

The first one is nice, because it will work neatly with fractional percentages.

You could wrap this up into a function like this:

function chance(percentage)
	return math.random() < percentage / 100
	-- or equivalently, math.random() * 100 < percentage
end

if chance(15) then
	print("15% of the time")
else
	print("85% of the time")
end

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