Oh no! I got an error! But why?

If you get this error it probably means you have too many function arguments, local variables or return values in your function.

Christian Reitwiessner, creator of Solidity, says this:

There are several situations in which this or similar errors occur. Most are related to too many local variables, parameters or return variables in functions. It might also happen if you have expressions that are too deeply nested.

Don’t worry, if you can’t reduce these things there is a simple solution. Use structs.

A single struct can hold multiple values. Put some of your local variables in a struct and then use the struct.

The implementation of the diamondCut function from the diamond standard uses this trick.

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

Full code in DiamondFacet.sol.