Solidity - 035 WhileLoop

本文介绍了一个Solidity智能合约,展示了如何使用while循环遍历映射存储的区块编号,并通过事件依次发出这些存储的数值。合约包含一个存储区块数的映射、计数器以及设置和获取存储数值的方法。
摘要由CSDN通过智能技术生成

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

/**

 * @title whileLoop

 * @dev Demonstrates the use of a while loop to iterate over a mapping in Solidity.

 * The contract stores block numbers at different instances and provides a function

 * to emit these stored values through an event.

 */

contract whileLoop {

    // Mapping to store block numbers. The key is an incrementing counter, and the value is the block number.

    mapping (uint => uint) blockNumber;

    // Counter to keep track of the number of entries in the mapping.

    uint counter;

    // Event to emit the stored block number.

    event uintNumber(uint);

    /**

     * @dev Stores the current block number in the mapping under the current value of `counter`.

     * Increments `counter` after storing the block number.

     */

    function setNumber() public {

        blockNumber[counter++] = block.number;

    }

    /**

     * @dev Emits the stored block numbers sequentially by iterating over the mapping

     * with a while loop. It starts from the first stored block number and continues

     * until it reaches the last stored block number based on the `counter`.

     */

    function getNumbers() public {

       uint i = 0; // Initialize the index for iteration.

       // While loop to go through each stored block number.

       while (i < counter) {

           // Emit an event with the current block number.

           emit uintNumber(blockNumber[i]);

           i = i + 1; // Increment the index to move to the next block number.

       }

    }

}

//Deploy:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值