Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- table MUST be a dictionary and have a weight entry!
- local function CalculateMaxWeight(aTable)
- local result = 0
- -- add all entries weights together, to get one big value
- for _, entry in pairs(aTable) do
- result = result + entry.Weight
- end
- return result
- end
- return function(aWeightedTable)
- -- Choose a random number between 0 and the max weight
- local MaxWeight = CalculateMaxWeight(aWeightedTable)
- local randI = math.random(MaxWeight)
- -- iterate the entries to see wich will be choosed based on their weight
- for _, entry in pairs(aWeightedTable) do
- -- the random number is lower than the current entry weight? Tehn return me that entry IT WAS SELECTED
- if randI <= entry.Weight then
- return entry
- else -- Substract and keep rolling
- randI = randI - entry.Weight
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement