I got this code from another devforum post that acts like a crate system with weights
local Items = {["Stick"] = 400, ["Club"] = 125, ["Sword"] = 50, ["Shield"] = 40}
local function GetRandom(set)
local sum = 0
for k, v in pairs(set) do
sum = sum + v
end
local r = math.random(sum)
for k, v in pairs(set) do
r = r - v
if r <= 0 then
return k
end
end
end
print(GetRandom(Items))
I studied it for a bit and got a little understanding on how it works generally. However, i cant seem to find a way to calculate the weights in percentage. I can understand the fact that, if there are 5 varaibles in a set with the same weight, the percentage for all of them would be 100 / the number of variables. But when one variable has a different weight, thats when i reach a dead end. Is there a proper formula on how to calculate these percentages? Any help would be appreciated!