Solidity Storage Struct Array – How to Properly Clear Arrays

arrayssoliditystoragestruct

We're implementing a Lottery where a player can buy multiple tickets.

A ticket is defined with a struct and they are being kept in a storage struct[]:

pragma solidity >=0.4.22 <0.9.0;

contract Lottery {

    struct Ticket {
        address payable playerAddress;
        uint256 potAtParticipation;
        uint256 potWithStake;
    }

    Ticket[] tickets;

    constructor() {
       _createLottery();
    }

After a specific block a winner gets determined and the lottery should be restarted. Therefore, we'd like to reset the tickets:

  function _createLottery() internal {
      tickets = new Ticket[](0); //this is not working as intended
    }
}

We're now facing the issue, that the code above does not empty/reset the array, due the combination of being a storage struct array – which makes sense.

But here we're stuck. What other approaches are there to accomplish a reset of our tickets?

We've seen ideas such as use delete (Understanding more about delete keyword in solidity) and pop. But it seems not to be doing quite the job / feels too complicated.

What would be the best practice/a good approach here?

Thanks for any inputs!

Best Answer

Not sure why delete should feel complicated.

    function _createLottery() internal {
      delete tickets;
    }

It essentially resets the whole storage array by 'zeroing' out all data that you have entered and setting .length to 0.

Related Topic