[英]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我使用的版本是0.5.2
I'm executing the below code in Remix IDE我在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():在函数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我正在尝试将我的玩家数组全部重置为 0,以便重置我的彩票合同
Probably the best/easiest thing to do is players.length = 0
.可能最好/最简单的事情是
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."然后只需执行
playersLength = 0
即可“重置”。
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:
这是在 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.在我的测试中,使用 JavaScript VM,
deleteFoo
消耗 26,070 gas, deleteBar
消耗 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.