简体   繁体   中英

How to assign or reset the address[] payable variable in solidity 0.5.2 or above?

The version I'm using is 0.5.2

I'm executing the below code in Remix IDE

pragma solidity  ^0.5.2;

contract Lottery {
    address public manager;
    address payable[] public players;

    constructor () public {
        manager = msg.sender;
    }

    function enter() public payable {
        require(msg.value > 0.01 ether);
        players.push(msg.sender);
    }

    // function getPlayers() public view returns(address[] memory) {
    //     return players;
    // }

    function random() public view returns(uint) {
        return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));
    }

    function pickWinner() public {
        uint index = random() % players.length;
        players[index].transfer(address(this).balance);
        players = new address[](0); // This line of code giving an error
    }
}

The error I'm getting is:

Type address[] memory is not implicitly convertible to expected type address payable[] storage ref.

in the function pickWinner():

function pickWinner() public {
    uint index = random() % players.length;
    players[index].transfer(address(this).balance);
    players = new address[](0); // This line of code giving an error
}

I'm trying to reset my players' array all to 0 so as to reset my Lottery contract

Probably the best/easiest thing to do is players.length = 0 .

Note that this will use gas proportional to the number of elements in the array (because it deletes all of them). If this is a problem, you might want to consider using a mapping instead with a separately stored length. Eg

mapping(uint256 => address payable) players;
uint256 playersLength;

Then just do playersLength = 0 to "reset."

EDIT

Per the comments, it sounds like you're not seeing the gas usage based on the size of the array. Here's a simple way to test in Remix:

pragma solidity 0.5.2;

contract Test {
    uint256[] foo;
    uint256[] bar;

    constructor() public {
       for (uint256 i = 0; i < 5; i++) { 
           foo.push(i);
       }
       for (uint256 i = 0; i < 100; i++) {
           bar.push(i);
       }
    }

    function deleteFoo() external {
        foo.length =  0;
    }

    function deleteBar() external {
        bar.length = 0;
    }
}

In my testing, using the JavaScript VM, deleteFoo consumes 26,070 gas, and deleteBar consumes 266,267 gas.

function pickWinner() public {
    uint index = random() % players.length;
    players[index].transfer(address(this).balance);
    players = new address payable [](0); //add payable to this line
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM