0

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.

Saphire
  • 111
  • 5

1 Answers1

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.

Yetik
  • 339
  • 1
  • 10