Loop

Looping in Solidity is tricky.

The number of iteration in a loop can grow and spend more gas than the gas limit, causing your contract to stall.

There are two gas limits to keep in mind.

  • Transcation gas limit, set by the caller.
  • Block gas limit

Try to avoid writing loops that you cannot estimate the gas consumption.

pragma solidity ^0.5.11;

contract Loop {
    uint public count;

    // This is a demonstration of transaction gas limit.
    // Try:
    // Set the gas limit to 100000 and loop(100).
    // It should throw an error after spending all the gas.
    function loop(uint n) public returns (uint) {
        for (uint i = 0; i < n; i++) {
            count++;
        }

        return count;
    }
}

Try on Remix