Files
bworld/docs/modding/inventories/containers.md
T
2026-11-14 12:18:41 -03:00

1.7 KiB

Containers

A container is a list of item slots that the server owns and saves: a chest's contents, a furnace's input, fuel and result, a player's inventory. The server phase makes and uses them through ctx.containers.

Making Containers

const container = ctx.containers.create(27); // 1 to 256 slots, saved with the world
const id = container.id; // keep this, like in a block's tile data

ctx.containers.get(id); // the container, or undefined once it's deleted
ctx.containers.delete(id); // closes any screen showing it

Containers are saved with the world until they're deleted. A block that owns one keeps its id in tile data, and deletes it when it's broken.

Using Containers

interface Container {
	readonly id: string;
	readonly size: number;
	get(slot: number): ItemStack | undefined; // live, see below
	set(slot: number, item: ItemStack | undefined): void;
	add(item: ItemStack): ItemStack | undefined; // fills matching stacks, then empty slots. returns what didn't fit
	on_change(fn: (slot: number) => void): () => void; // returns a function that stops watching
}
container.set(0, { id: "bworld:coal", count: 8 });
const left = container.add({ id: "bworld:coal", count: 100 });
if (left) ctx.world.drop_item(x, y, z, left);

Stacks from get are live: setting count or data changes the stack in the container, and a stack counted down to 0 is gone. set and add copy what they're given.

Changes are synced to every player viewing the container, whether a script or a player made them.

A player's inventory is a container too, player.inventory, with the hotbar in slots 0-8.

To let players see and use a container, give them a menu with its slots.