83 lines
1.9 KiB
Lua
83 lines
1.9 KiB
Lua
local item = require("item")
|
|
|
|
local itemstack = {}
|
|
local prototype = {}
|
|
|
|
function prototype:isBlank()
|
|
return self.item == nil
|
|
end
|
|
|
|
function prototype:availableCount()
|
|
return self.itemLimit - self.count
|
|
end
|
|
|
|
function prototype:canTransferTo(otherStack)
|
|
if self:isBlank() or ((not otherStack:isBlank()) and self.item ~= otherStack.item) then
|
|
return 0
|
|
end
|
|
|
|
local availableCount = otherStack:availableCount()
|
|
if availableCount >= self.count then
|
|
return self.count
|
|
end
|
|
|
|
return availableCount
|
|
end
|
|
|
|
local metatable = {
|
|
__eq = function(a, b)
|
|
return a.item == b.item and
|
|
a.count == b.count and
|
|
a.itemLimit == b.itemLimit
|
|
end,
|
|
__metatable = nil,
|
|
__index = prototype,
|
|
__tostring = function(ser)
|
|
return textutils.serialise({
|
|
item = tostring(ser.item),
|
|
count = ser.count,
|
|
itemLimit = ser.itemLimit
|
|
}, { compact = true })
|
|
end
|
|
}
|
|
|
|
local function newItemStack(itemInst, count, itemLimit)
|
|
local stack = {
|
|
item = itemInst,
|
|
count = count,
|
|
itemLimit = itemLimit
|
|
}
|
|
|
|
setmetatable(stack, metatable)
|
|
|
|
return stack
|
|
end
|
|
|
|
function itemstack.blank(itemLimit)
|
|
return newItemStack(nil, 0, itemLimit)
|
|
end
|
|
|
|
function itemstack.fromItemDetail(detail, itemLimit)
|
|
if detail == nil then
|
|
return itemstack.blank(itemLimit)
|
|
end
|
|
|
|
return newItemStack(item.fromDetail(detail), detail.count, itemLimit)
|
|
end
|
|
|
|
function itemstack.fromString(str)
|
|
local strStack = textutils.unserialize(str)
|
|
if type(strStack.item) ~= "string" or
|
|
type(strStack.count) ~= "number" or
|
|
type(strStack.itemLimit) ~= "number" then
|
|
error("Could not parse itemstack: "..str)
|
|
end
|
|
|
|
strStack.item = item.fromString(strStack.item)
|
|
|
|
setmetatable(strStack, metatable)
|
|
|
|
return strStack
|
|
end
|
|
|
|
return itemstack |