Solidity error solution for “Stack too deep, try removing local variables”
If you get this error it probably means you have too many function arguments, local variables or return values in your function.
Instead of declaring 6 local variables it declares a single local variable that is a struct holding the 6 variables. Here’s a snippet:
struct SlotInfo {
uint originalSelectorSlotsLength;
bytes32 selectorSlot;
uint oldSelectorSlotsIndex;
uint oldSelectorSlotIndex;
bytes32 oldSelectorSlot;
bool newSlot;
}
// Using the struct to avoid Stack too deep error
function diamondCut(bytes[] memory _diamondCut) public override {
SlotInfo memory slot;
slot.originalSelectorSlotsLength = $selectorSlotsLength;
... code omitted
if(selectorSlotLength > 0) {
slot.selectorSlot = $selectorSlots[selectorSlotsLength];
}
... code omitted for simplicity