Advertisement
Quoteory

Inventory With Recursion

Mar 28th, 2021
959
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.89 KB | None | 0 0
  1. local HTTPService = game:GetService("HttpService")
  2.  
  3. local itemInfos = { -- only here for example, this should be a module of its own
  4.     ["RedApple"] = {
  5.         DisplayName = "Red Apple",
  6.         MaxQuantity = 4,
  7.     },
  8.     ["GreenApple"] = {
  9.         DisplayName = "Green Apple",
  10.         MaxQuantity = 1,
  11.     }
  12. }
  13.  
  14. local Inventory = {}
  15. Inventory.__index = Inventory
  16.  
  17.  
  18. function Inventory.new(player)
  19.     local self = setmetatable({
  20.         Player = player,
  21.         Items = {},
  22.         ItemCount = 0,
  23.         MaxItems = 4,
  24.     }, Inventory)
  25.     return self
  26. end
  27.  
  28. function Inventory:GetHighestOpenItem(itemName)
  29.     local itemInfo = assert(itemInfos[itemName], "Invalid Item Name")
  30.     local highestItem = nil
  31.     local highestQuantity = 0
  32.    
  33.     for uuid, item in pairs(self.Items) do
  34.         if item.ItemName == itemName and item.Quantity > highestQuantity and item.Quantity < itemInfo.MaxQuantity then
  35.             highestItem = item
  36.             highestQuantity = item.Quantity
  37.         end
  38.     end
  39.    
  40.     return highestItem
  41. end
  42.  
  43. function Inventory:AddItem(itemName, itemQuantity)
  44.     local itemInfo = assert(itemInfos[itemName], "Invalid Item Name")
  45.     local highestOpenItem = self:GetHighestOpenItem(itemName)
  46.     local atInventoryMaxItems = self.ItemCount == self.MaxItems
  47.    
  48.    
  49.     local function addToItem(item) -- takes quantity from itemQuantity and gives it to the item
  50.         local quantityToTake = math.clamp(itemQuantity, 0, itemInfo.MaxQuantity - item.Quantity)
  51.         item.Quantity += quantityToTake
  52.         itemQuantity -= quantityToTake
  53.     end
  54.    
  55.     if itemQuantity > 0 then
  56.         if highestOpenItem then -- add to existing item
  57.             addToItem(highestOpenItem)
  58.             self:AddItem(itemName, itemQuantity)
  59.         elseif not atInventoryMaxItems then -- new item
  60.             local item = {
  61.                 ItemName = itemName,
  62.                 Quantity = 0,
  63.                 UUID = HTTPService:GenerateGUID(false)
  64.             }
  65.             addToItem(item)
  66.             self.ItemCount += 1
  67.             self.Items[item.UUID] = item
  68.             self:AddItem(itemName, itemQuantity)
  69.         end
  70.     end
  71. end
  72.  
  73. return Inventory
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement