2

Ethereum newbie here. I'm trying to implement a simple 4-number lottery game, based on the amount of Wei sent.

Example
Account 0 entered the lottery with 1234 Wei.
Account 1 entered the lottery with 5678 Wei.
If the manager ran pickWinner(1234), Account 0 will win and get the money since he entered with the winning number.

Problem
It seems like players = new Player[](0) is not allowed.

UnimplementedFeatureError: Copying of type struct Lottery.Player memory[] memory to storage not yet supported.

Is there any way to clear an array of structs? or is there a better way to approach this lottery mechanism? Thanks! :)

pragma solidity ^0.4.17;

contract Lottery {
address public manager;
struct Player {
    address recipient;
    uint value;
}
Player[] public players;

mapping(uint => address[]) recipientValue;
mapping(uint => uint) recipientValueCount;

function Lottery() public {
    manager = msg.sender;
}

function enter() public payable {
    Player memory newPlayer = Player({
        recipient: msg.sender,
        value: msg.value
    });

    players.push(newPlayer);

    recipientValue[msg.value].push(msg.sender);
    recipientValueCount[msg.value]++;
}


function pickWinner(uint index) public restricted {
    address[] storage winners = recipientValue[index];
    uint prize = this.balance / recipientValueCount[index];

    for(uint i=0; i< winners.length; i++){
        winners[i].transfer(prize);
    }

    players = new Player[](0);

} 

function totalBalance() public view returns (uint) {
    return this.balance;
}


modifier restricted() {
    require(msg.sender == manager);
    _;
}

}

2 Answers 2

1

You can't copy a memory array type into a storage one, the new Player[](0) is in memory and your players variable is in storage wince it is a state variable of your contract so, due to solidity not implementing that yet you can't do what you did.

clearing an array of variables would probably be hard. What you can do is put them to Zero by using delete players[i] with i the index of a loop ;

for(uint i =0; i < players.length; i++){
   delete players[i];
}
2
  • happy to serve ! Commented Feb 22, 2018 at 7:40
  • But the players.length is not be reverted back to zero? How we can do it without having the length managed externally?
    – kitta
    Commented Oct 26, 2021 at 9:11
0

Sorry for necroposting, but actually this problem appears even on 0.8.7 version of solidity compiler. So I would suggest this kind of solution.

    function clearPlayers() private {
       while(_players.length != 0) {
          _players.pop();
       }
}

And after running of this code, _players array will be empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.