Testing for equality in elements of struct in a for loop (Invalid Opcode)

Viewed 15

I am trying to test for equality in a for loop, and then execute a function if those conditions are met, like so:

pragma solidity ^0.5.0; 


contract Types { 

  struct Player {
    string hasplayed;
    address my_address;
    uint wager;
  }

  Player[] public players; 

  uint[] data;

  function initialize(uint wager) public {
    players.push(Player("no", msg.sender, wager));  
  } 

  function length() public returns(uint) {
      uint len = players.length;
      return len;

  }

  function loop(
  ) public returns(uint[] memory){

  uint len = players.length;

  for(uint i=0; i<len; i++){
      Player storage myplayer = players[i];
      Player storage newestplayer = players[len];
      if (myplayer.wager == newestplayer.wager) {
          flip();
      }
      // take newest player wager value and compare to pasts, 'if' match, execute function which does roll
      data.push(myplayer.wager);
  }
    return data;
  }

  function flip() public view returns(string memory) {
      return "flip";
  }
}

I initialize four players, two with the same wager (which is what is being tested for).

When I run the loop function, I get an invalid opcode, but not much other information (From Remix IDE, feel free to recommend others that might help with debugging, or clarify how to debug more on Remix).

I simply want the code to run the Roll function when the equality test is met, how can I achieve this?

1 Answers

I initialize four players

The players array now contains 4 items with indexes 0-3.

uint len = players.length; assigns 4 to the len variable, as that's the array length.

Player storage newestplayer = players[len]; Here you're trying to access players[4], which does not exist (the highest index is 3), and it throws the exception.


Solution: The newest player is at index len-1.

Player storage newestplayer = players[len-1];
Related