How do I get this to randomize

I want it to choose a random ability based on the chance number in the table Abillities.

How do I do this?

local abillities = {}

abillities.Abillities = {
	["Abillity1"] = {
		["Function"] = function()
			
		end,
		["Chance"] = 100,
	},
}

function abillities.PickAbillity(abillitystring)
	local abillity = abillities.Abillities[abillitystring]
	if abillity then
		abillity.Function()
	end
end

function abillities.RandomizeAbillity()
	local chances
	for i,v in pairs(abillities.Abillities) do

	end
end

return abillities

forgot how to exactly do this but it’s something like this:
(edit, forgot you wanted chances)

local maxchance = 0

for i, v in abilities.Abilites do

     if v and v.Chance then maxchace += v.Chance

end

local random = math.random(1, maxchance)

for i, v in abilites.Abilites do

     if not v or not v.Chance then continue end
     
     random -= v.Chance

     if random <= 0 then

          return v

     end

end
2 Likes

You need to make weighted chance system Weighted Chance System

2 Likes

Thank you this topic helped a lot

New code:

function abillities.RandomizeAbillity()
	local Weight = 0
	
	for _, v in pairs(abillities.Abillities) do
		Weight += (v.Chance * 10)
	end
	
	local rNumber = math.random(1,Weight)
	
	Weight = 0
	
	for i,v in pairs(abillities.Abillities) do
		Weight += (v.Chance * 10)
	
		if Weight >= rNumber then
			print(v.Name)
			break
		end
	end
end

return abillities
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.