0

Please how do i map addresses to each array

I have parameters of an array inside an array, and i want to map each array to each address, please how do I go about this? thanks

contract SolahParchiThap {

address owner = msg.sender;
modifier onlyOwner {require(msg.sender == owner); _;}

mapping(address => uint[]) _players;

// To set and start the game
function setState(address[4] memory players, uint8[4][4] memory parchis) view public onlyOwner returns (string memory){
    
    for (uint i=0; i <= players.length; i++){
        if (players[i] == owner){
            return ("Owner can not be a player");
        } else {
            
        }
    }    
}

}

1 Answer 1

0

How about codes below?

contract SolahParchiThap {

    address owner = msg.sender;
    modifier onlyOwner {require(msg.sender == owner); _;}

    mapping(address => uint8[]) _players;

    // To set and start the game
    function setState(address[] memory players, uint8[][] memory parchis) public onlyOwner returns (string memory){
        
        for (uint i=0; i < players.length; i++){
            if (players[i] == owner){
                return ("Owner can not be a player");
            } else {
                _players[players[i]] = parchis[i];
            }
        }

        return ("Succeeded");
    }
}

I changed 6 points from your source.

  1. Mapping variable's type declaration
  • It seems that a mappinng variable _players stores (player's addres => player's parchis).
    In your source, mapped value type was declared as array of uint, but your function receives array of uint8.
    If you want to store recived parchis, mapped value type also should to be declared as array of uint8.
  1. View option in function's declaration
  • Your function may change member variable _players.
    So it is not view function. It must be removed.
  1. Length of Array in function's declaration
  • Because there is a loop for each player in your source, I think that length of players parameter will be variable.
    So I removed length specifications to each array.
  1. Loop condition
  • It is wrong that i <= players.length.
    It should be i < players.length.
  1. Add store procedure
  • At else case of player's address check (in player for-loop), I added a procedure which stores received parchis.
    It is a simple usage of mapping type.
  1. Add succeeded return value
  • End of your function, add return procedure when succeeded.

I hope this helps.

2
  • It works, thanks, you are awesome...I will keep learning, I see I made little mistakes here and there Commented Oct 15, 2023 at 13:25
  • I'm happy too it works well. You can check the answer to close it. :) Commented Oct 15, 2023 at 13:47

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.