Skip to content
Advertisement

Making use of a nested Array with solidity

I need to create an online game using solidity. The games have games within them with each game having their respective players. it can be likened to a battle royale on a FPS game where there are various battle royales going on simultaneously within the game with their respective participants. I tried using an array within a struct to keep record of the games. However, I have been facing error after error trying to do this.

The Struct:

struct Game {
        address[] participants;
        uint amountRequired;
        uint Duration;
        uint id;
        bool ended;
        uint createdTime;
    } 

The function to create the game:

function CreateGame(uint amountRequired, string memory timeoption) public restricted{
        setGameDuration(timeoption);
        gameid++;

        Game memory newGame = Game({
            participants: address[] participants,
            amountRequired: amountRequired,
            Duration: gametime,
            id: gameid,
            ended: false,
            createdTime: block.timestamp

        });
        
    }

Advertisement

Answer

You need to initialize the array on a separate line, and then pass it to the struct. See the _participants variable in the snippet:

pragma solidity ^0.8;

contract MyContract {
    struct Game {
        address[] participants;
        uint amountRequired;
        uint Duration;
        uint id;
        bool ended;
        uint createdTime;
    }

    // create a storage mapping of value type `Game`
    // id => Game
    mapping(uint => Game) public games;

    function CreateGame(uint amountRequired, string memory timeoption) public {
        // dummy values
        address[] memory _participants; // empty array by default
        uint gametime = 1;
        uint gameid = 1;

        Game memory newGame = Game({
            participants: _participants,
            amountRequired: amountRequired,
            Duration: gametime,
            id: gameid,
            ended: false,
            createdTime: block.timestamp
        });

        // store the `memory` value into the `storage` mapping
        games[gameid] = newGame;
    }

    function addParticipant(uint gameId, address participant) public {
        require(games[gameId].createdTime > 0, "This game does not exist");
        games[gameId].participants.push(participant);
    }
}

If you want to set some participants in the code (not passed from an argument), working with dynamic array in memory is a bit tricky. See this answer for more info and an example.

Edit: To add participants to the array in a separate function, you need to store the Game in a storage variable first. See the games mapping in my update snippet. Then you can .push() into the storage array from a separate function.

Advertisement