Lesson 3 of 10

The player's inventory

Goal

Capped stacks and returning the overflow

01

Explanation

Any game where the player collects things needs an inventory with a limited number of slots, and each slot holds a stack of one kind of item up to a cap, like 64 in Minecraft. There may not be room for everything the player picked up, so the add function doesn't hide the overflow. It returns it instead, and the leftovers stay on the ground or the pickup is refused.

Adding happens in two passes: first you top up the partial stacks of the same item, then you open new stacks in empty slots. The slots are stored in a slots table that has gaps, where each slot is either nil or a table like { item = "arrow", count = 7 }. So loop over it with for i = 1, self.size, not with ipairs, which stops at the first empty slot.

Be careful when removing. If you reduce the stacks one after another and find out halfway through that there isn't enough, you leave the inventory only partly changed, and on a game server that opens the door to exploits that duplicate or lose items. So check the total first, and don't change anything until you know the whole operation will go through.

02

Your task

Complete Inventory:add(item, amount) so it tops up the partial stacks of item and then fills empty slots, without letting any stack go over maxStack, and then returns whatever didn't fit, which is zero if everything fit. Then complete Inventory:remove(item, amount) so it returns false without changing anything if there isn't enough. Otherwise it reduces the amount, empties every slot whose count reaches zero, and returns true.

Checks

6 checks
  1. The add function returns whatever didn't fit
  2. A partial stack is topped up before a new slot is opened
  3. Different items don't mix in one stack
  4. The remove function reduces the amount and returns true
  5. Removing more than there is returns false and changes nothing
  6. A slot that empties becomes available again
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.