Adding items to the first matching stack and then clamping it to the stack limit silently throws the extra away, and adding without the clamp makes a stack bigger than the limit. In our Godot 4.7 test, 250 herbs added to a stack of 90 with a limit of 99 left 99 herbs and lost 241 with the clamp, and made one stack of 340 without it. Topping up the stack and putting the rest into new slots gave 99, 99, 99 and 43, all 340 herbs, and when the bag was full the script handed back the 44 that did not fit.
The code
Save it as stack_add.gd, load it with const StackAdd := preload("res://stack_add.gd") and add items with var left := StackAdd.add(slots, "spirit_herb", 250, 99, 20): the item, how many, the stack limit and how many slots the bag has. The slots are an Array of Dictionaries with an item and a count. If left is more than 0, drop that many on the ground, or refuse the pickup.
extends RefCounted
## Adds items to an inventory with a stack limit: tops up the stacks of that
## item first, opens new slots for the rest, and gives back what did not fit,
## so nothing is lost and no stack goes over the limit.
## var left := StackAdd.add(slots, "spirit_herb", 250, 99, 20)
## if left > 0:
## drop_on_ground("spirit_herb", left) # or refuse the pickup
## slots is an Array of Dictionaries {"item": String, "count": int}.
static func add(slots: Array, item: String, count: int, max_stack: int, max_slots: int) -> int:
for s in slots: # 1) top up stacks that are not full yet
if count <= 0:
break
if s["item"] == item and s["count"] < max_stack:
var put := mini(count, max_stack - int(s["count"]))
s["count"] += put
count -= put
while count > 0 and slots.size() < max_slots: # 2) new stacks in empty slots
var put := mini(count, max_stack)
slots.append({"item": item, "count": put})
count -= put
return count # 3) what did not fit
static func total(slots: Array, item: String) -> int:
var n := 0
for s in slots:
if s["item"] == item:
n += int(s["count"])
return n
What we measured
A bag of 5 slots holding herbs 90 and ore 10, with a stack limit of 99, then 250 herbs added. Two runs gave the same results.
- Add to the first herb stack, then clamp to 99: [herb 99, ore 10]. 99 herbs of 340, 241 lost.
- Add to the first herb stack with no check: [herb 340, ore 10], a stack 3 times the limit.
- The script: [herb 99, ore 10, herb 99, herb 99, herb 43], all 340 herbs, nothing left over, no stack over 99.
- 100 more herbs into that bag: the 43 topped up to 99, the bag full, 44 handed back. 396 in the bag plus 44 handed back is 440, exactly what went in.
- 5 ore into the full bag: they went onto the ore stack, 15, nothing handed back.
- 10,000 random pickups of 1 to 60 of four items into 20 slots, with items used up now and then: every item was either in the bag or handed back, and no stack ever went over 99.
Why it happens
mini(count + n, 99) answers how many fit in this stack, but the rest of n has to go somewhere, and nothing in that line sends it anywhere. Without the clamp the stack just keeps growing. The script works in three steps: top up every stack of that item that is not full, open new slots for whole stacks while there is room, then return the count that is left so the caller decides what happens to it.
What to change
- A recipe that says not enough herbs when you have enough across two stacks: count across stacks. Recipes that should accept ingredients in any order: any-order recipes.
- Saving the bag so the counts come back as ints: a JSON save that keeps types.
A whole pill refining system to fill the bag from: the Xianxia Alchemy & Pill Refining System for Godot 4 has herbs, recipes, a furnace heat minigame, experimenting to discover recipes, levels and save/load.
Tested in Godot 4.7 with the Compatibility renderer.
Ready-made: Xianxia Alchemy & Pill Refining System for Godot 4 has herbs, recipes, a furnace heat minigame, experimenting to discover recipes, levels and save/load.
More how-tos: Game systems
- Hover a 3D object inside a SubViewport
- A turned building that covers the cells it stands on
- A JSON save that loads back exactly what you saved
- Fire that spreads one cell per step, in every direction
- A pooled enemy that comes back as fresh as a new one
- An enemy that stops at the dead player and finds the respawned one
- Poison, burn and bleed that keep ticking when applied again
- XP, qi and gold that keep growing without going negative
- Count slot line wins with wilds in front
- Random directions spread evenly over a sphere or a cone
- Count a lap only when the car really went round
- Make a seed repeat: daily runs, replays and roguelike seeds
- Offline progress that counts the time the game was closed
- A chance roll without the long bad-luck streaks
- Check crafting recipes in any order, with the right counts
- Make HP and mana regen the same at any frame rate
- Damage over time with the right number of ticks
- Spawn enemies where the camera cannot see them
- Keep a chasing horde from stacking into one enemy
- Make the fish bite after the same wait at any frame rate
- Snap buildings to the right grid cell on both sides of the origin
- Make a cooking timer fire once, on time
- Pick from a weighted loot table with the right chances
- Level up as many times as the XP covers
- Walk a patrol guard to each point without overshooting
- Remove items from an Array while checking them, without skipping any
- Scatter spikes, roots or trees in a circle without overlaps
- Count and take crafting items from every stack
- Play random sounds and events without obvious repeats
- Pick the growth image so the ripe one shows exactly when the crop can be picked
- Turn a day counter into season, day and year without a day 0
- An enemy that dies once, however many hits land
- A fair shuffle you can replay
- A ghost that drives the lap at real speed
- A vision cone that does not flicker at the edge
- Move a group of units without a pile-up
- A sprinkler that waters a round patch
- A slot reel that always lands forward on the result
- A crowd of NPCs that never emote or bob in step
- A song position that moves on every frame
- Nodes your editor tool adds that stay in the scene