Skip to content

Instantly share code, notes, and snippets.

@Elmuti
Created May 20, 2015 19:45
Show Gist options
  • Save Elmuti/e0fac91406566b234793 to your computer and use it in GitHub Desktop.
Save Elmuti/e0fac91406566b234793 to your computer and use it in GitHub Desktop.
local Inventory = {}
local mobj = require("System/Libraries/ModObject")
local Signal = require("System/Classes/Signal")
Inventory.ItemAdded = Signal.New()
Inventory.ItemRemoved = Signal.New()
function Inventory.Create(itemsTable)
local inv = Inventory:Init()
inv.Items = itemsTable or {}
return inv
end
function Inventory:UseItem(item)
item:Use()
self:RemoveItem(slot)
end
--Adds item "item" in slot "slot"; if "slot" is nil, then adds the item in slot "#self.Items + 1"
function Inventory:AddItem(item, slot, cb)
self.Items[slot or (#self.Items + 1)] = item
self.ItemAdded:Fire(item)
if cb ~= nil then
cb()
end
end
--Removes item in slot "slot"
function Inventory:RemoveItem(slot, cb)
self.ItemRemoved:Fire(self:GetItemInSlot(slot))
table.remove(self.Items, slot)
if cb ~= nil then
cb()
end
end
--Gets the item in the inventory slot of "slot"
function Inventory:GetItemInSlot(wantedSlot)
for slot, item in pairs(self.Items) do
if slot == wantedSlot then
return item
end
end
return nil
end
--Swap item in "slot1" to "slot" and vice versa
function Inventory:SwapItems(slot1, slot2)
local item1, item2 = self:GetItemInSlot(slot1), self:GetItemInSlot(slot2)
self:RemoveItem(slot1)
self:RemoveItem(slot2)
self:AddItem(item1, slot2)
self:AddItem(item2, slot1)
end
--Clears the inventory
function Inventory:Clear()
self.Items = {}
end
local InventoryClass = mobj:NewClass("Inventory", nil, Inventory)
return InventoryClass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment