Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local HTTPService = game:GetService("HttpService")
- local itemInfos = { -- only here for example, this should be a module of its own
- ["RedApple"] = {
- DisplayName = "Red Apple",
- MaxQuantity = 4,
- },
- ["GreenApple"] = {
- DisplayName = "Green Apple",
- MaxQuantity = 1,
- }
- }
- local Inventory = {}
- Inventory.__index = Inventory
- function Inventory.new(player)
- local self = setmetatable({
- Player = player,
- Items = {},
- ItemCount = 0,
- MaxItems = 4,
- }, Inventory)
- return self
- end
- function Inventory:GetHighestOpenItem(itemName)
- local itemInfo = assert(itemInfos[itemName], "Invalid Item Name")
- local highestItem = nil
- local highestQuantity = 0
- for uuid, item in pairs(self.Items) do
- if item.ItemName == itemName and item.Quantity > highestQuantity and item.Quantity < itemInfo.MaxQuantity then
- highestItem = item
- highestQuantity = item.Quantity
- end
- end
- return highestItem
- end
- function Inventory:AddItem(itemName, itemQuantity)
- local itemInfo = assert(itemInfos[itemName], "Invalid Item Name")
- local highestOpenItem = self:GetHighestOpenItem(itemName)
- local atInventoryMaxItems = self.ItemCount == self.MaxItems
- local function addToItem(item) -- takes quantity from itemQuantity and gives it to the item
- local quantityToTake = math.clamp(itemQuantity, 0, itemInfo.MaxQuantity - item.Quantity)
- item.Quantity += quantityToTake
- itemQuantity -= quantityToTake
- end
- if itemQuantity > 0 then
- if highestOpenItem then -- add to existing item
- addToItem(highestOpenItem)
- self:AddItem(itemName, itemQuantity)
- elseif not atInventoryMaxItems then -- new item
- local item = {
- ItemName = itemName,
- Quantity = 0,
- UUID = HTTPService:GenerateGUID(false)
- }
- addToItem(item)
- self.ItemCount += 1
- self.Items[item.UUID] = item
- self:AddItem(itemName, itemQuantity)
- end
- end
- end
- return Inventory
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement