% based math.Random

Hello everyone, in this script I am trying to make it so that if you get a % you can get your percentage. For example, lets just say there was a common that has a 22% chance of you getting, and it would say “common 22% chance” received. so far i’ve looked at weighted values and stuff like that but nothing seemed to work. Right now the script below isnt percentage, and I would have to go get decimals of 50 if I wanted lets just say a 0.5% chance at something.

local Num = 100
local list = 0 

local function RNGesus()
	local percentOfNum = math.floor(math.random()*Num)
	
	if percentOfNum == 1 then
		print("1")
	end
	
	-- So on, so forth... (till I reach 50.)
	list = list + 1
	print(percentOfNum)
	
end
RNGesus()

As you can see from the script, i wouldve had to make a “percentageOfNum == 1 through 50” all the way until I was done. Is there any way of optimizing this with percentages?

Thanks in advance

Yes, this looks alright. I would say so, indeed.

Here’s a possible concept that you could use:

local rates = {
 {
  rate = 10,
  name = "TestA"
 },
 {
  rate = 90,
  name = "TestB"
 }
}

function roll()
 local totalRate = 0
 for i,v in pairs(rates) do
  totalRate += v.rate
 end
 
 local chosenRate = math.random()*totalRate
 local currentRate = 0
 local chosenItem
 for i,v in pairs(rates) do
  currentRate += v.rate
  if currentRate >= chosenRate then
   chosenItem = v
   break
  end
 end
 return chosenItem
end

local result = roll()
print(result.name)

This is essentially a weight system where the chance of something is localRate/totalRate. eg. “TestA” is 10/100 or 10%.

1 Like