Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Backpack = {
- list = {}
- }
- setmetatable(Backpack, {
- __call = function (self, ...)
- return self:create(...)
- end
- })
- function Backpack:create(player, slots)
- if Backpack.list[player] then
- return Backpack.list[player]
- end
- local new = {
- items = {},
- slots = slots or 20,
- owner = player
- }
- setmetatable(new, {__index = Backpack})
- Backpack.list[player] = new
- return new
- end
- function Backpack:getSlots()
- return self.slots
- end
- function Backpack:getEmptySlot()
- for i = 1, self.slots do
- if not self.items[i] then
- return i
- end
- end
- return false
- end
- function Backpack:getItems(withAmount)
- local items = {}
- for index, slot in pairs(self.items) do
- if not withAmount then
- items[#items + 1] = slot.item
- else
- items[#items + 1] = slot
- end
- end
- return items
- end
- function Backpack:hasItem(item)
- for index, slot in pairs(self.items) do
- if slot.item == item then
- return true
- end
- end
- return false
- end
- function Backpack:getOwner()
- return self.owner
- end
- function Backpack:addItem(item, amount)
- if not self:hasItem(item) then
- local slot = self:getEmptySlot()
- if slot then
- self.items[slot] = {item = item, amount = amount}
- return true
- else
- return false
- end
- else
- for index, slot in pairs(self.items) do
- if slot.item == item then
- slot.amount = slot.amount + amount
- return true
- end
- end
- return false
- end
- end
- function Backpack:removeItem(item, amount)
- if not self:hasItem(item) then
- return false
- end
- for index, slot in pairs(self.items) do
- if slot.item == item then
- if not amount or (slot.amount - amount) <= 0 then
- self.items[index] = nil
- else
- slot.amount = slot.amount - amount
- end
- return true
- end
- end
- return false
- end
- function Backpack:getWeight()
- local weight = 0
- for index, slot in pairs(self.items) do
- weight = weight + (slot.item:getWeight() * slot.amount)
- end
- return weight
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement