Advertisement
Guest User

LootManager Module

a guest
Jul 27th, 2020
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.42 KB | None | 0 0
  1. local module = {}
  2.  
  3.  
  4. local function usingWeights(slots)
  5.     for i, v in pairs(slots)do
  6.         if(v.Weight)then
  7.             return true
  8.         end
  9.         return false
  10.     end
  11. end
  12.  
  13.  
  14. --[[
  15.     Gets total weight between all slots
  16. ]]
  17. function module:GetTotalWeight(slots)
  18.     local total = 0
  19.     for _, slot in pairs(slots) do total = total + slot.Weight end
  20.     return total
  21. end
  22.  
  23.  
  24. --[[
  25.     Selects a random slot from the table for you.
  26. ]]
  27. function module:GetRandomSlot(slots)
  28.     --get total weight/chances
  29.     local total = usingWeights(slots) and self:GetTotalWeight(slots) or 1
  30.     --get a random number based on total weight/chances
  31.     local randomNumber = math.random()*total
  32.    
  33.     --iterate through all slots and select a random one based on weights/chances
  34.     for _, slot in pairs(slots) do
  35.         local n = slot.Weight or slot.Chance
  36.         if  randomNumber <= n then
  37.             return slot
  38.         else
  39.             randomNumber = randomNumber - n
  40.         end
  41.     end
  42. end
  43.  
  44.  
  45. --[[
  46.     Convert Weights into percentages (for debugging purposes / visualization purposes)
  47.     You DONT need this function to create a table based on perctanges.
  48. ]]
  49. function module:GetChances(slots)
  50.     local chances = {}
  51.     local total = self:GetTotalWeight(slots)
  52.     for key, slot in pairs(slots)do
  53.         if(not slot.Weight)then return end
  54.  
  55.         chances[key] = {Chance = slot.Weight / total}
  56.        
  57.         for i, v in pairs(slot) do
  58.             if(i ~= "Weight") then
  59.                 chances[key][i] = v    
  60.             end
  61.         end
  62.     end
  63.     return chances
  64. end
  65.  
  66.  
  67.  
  68.  
  69. return module
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement