This might seem basic, but I'm trying to loop through an array from the top n items down. submissionId is the basically the length of the array, but always +1 of the actual latest index.

function getLastNSubmissions(uint256 n) public view returns (string[6][] memory) {
    require(submissionId > 0, "There are no submissions yet.");

    string[6][] memory returnSubmissions = new string[6][](n);
    uint stop = 0;
    // Make sure stop isn't negative
    if ((submissionId-n) >= 0) stop = submissionId-n;

    uint pos = 0;
    for (uint i=(submissionId-1); i >= stop; i-=1) {
        if (i < 0) break;
        Submission storage s = submissions[i];

        returnSubmissions[pos][0] = // assign something
        returnSubmissions[pos][1] = // assign something
        returnSubmissions[pos][2] = // assign something
        returnSubmissions[pos][3] = // assign something
        returnSubmissions[pos][4] = // assign something
        returnSubmissions[pos][5] = // assign something

        pos += 1;
    return returnSubmissions;

But for some reason, this function errors when n is <= submissionId. This function only works, when n is lower than submissionId.

Expected result: If n is greater than submissionId, return all items available. Otherwise, return the last n items.

1 Answer 1


Because your variables are uint and when you try to substract n from submissionId you get negative value but both of your variables are unsigned integers. Change your if statement to this:

 if(submissionId > n) stop = submissionId - n;

And i in for statement should be int not uint.

*This is also cheaper for the gas, with only one comparison instead of 1 calculation and 1 comparison.

  • I applied your changes, but the problem still remains.
    – Saphire
    Commented Nov 9, 2022 at 10:22
  • Can you share your new code? I tried without a problem.
    – Yetik
    Commented Nov 13, 2022 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.