Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How would you make Precentage chance of something happening?

Asked by 7 years ago

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
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... Scarious 243 — 7y

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago

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
Ad

Answer this question