1

我使用的版本是0.5.2

我正在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
    }
}

我得到的错误是:

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

在函数 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
}

我正在尝试将我的玩家数组全部重置为 0,以重置我的彩票合同

4

2 回答 2

1

可能最好/最容易做的事情是players.length = 0.

请注意,这将使用与数组中元素数量成比例的气体(因为它会删除所有元素)。如果这是一个问题,您可能需要考虑使用映射而不是单独存储的长度。例如

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

然后只需要做playersLength = 0“重置”。

编辑

根据评论,听起来您没有看到基于阵列大小的气体使用情况。这是在 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;
    }
}

在我的测试中,使用 JavaScript VM,deleteFoo消耗 26,070 个 gas,deleteBar消耗 266,267 个 gas。

于 2019-01-16T09:25:38.937 回答
1
function pickWinner() public {
    uint index = random() % players.length;
    players[index].transfer(address(this).balance);
    players = new address payable [](0); //add payable to this line
}
于 2021-11-11T10:04:45.733 回答