I'm creating a crate that gives items to people, but I want the ability where I can make it so the items have a percentage of being given out, so itemA may have a 10 percent chance, where as itemB has a 90 percent chance. I know you can use math.random with percentages but using it in a list I'm not sure how to do. I'm planning on adding a lot of items which is why I want to put it in a list so I can continue to add.
I know you can do:
math.random(10, 100) --or math.random(90, 100)
but giving that to an item not sure.
I'm really not sure on what to do to be honest. Any help would be appriciated.
From https://scriptinghelpers.org/questions/26333/randomly-giving-item-with-percentage#29907
local items={ {w=4,item=CommonAxe}, {w=1,item=RareAxe} } local wsum=0 for i=1,#items do wsum=wsum+items[i].w end function chooseItem() local itemn=math.random(wsum) local n=0 for i=1,#items do n=n+items[i].w if n>=itemn then return items[i].item end end end
A random number is chosen from the sum of weights of items, and the weights are added in order until the sum reaches the random number chosen. The weight landed on corresponds to the returned item.