Solidity

請問如何在solidity中創建嵌套數組

  • July 26, 2022

我試圖創建一個有多個房間的契約,每個房間都會有一些玩家。請問我該如何實現?這是我的方法,但它不起作用。我也無法返回映射數組。

contract TheGame {
   uint256 totalRoom;

   struct Room {
       address player;
       uint256 amount;
   }
   Room[] public room;

   mapping(uint256 => Room[]) public eachRoomNumberToEachRoom;

   function createRoom(uint256 _amount) public {
       room.push(Room({
           player: msg.sender,
           amount: _amount
       }));
       totalRoom += 1;
       eachRoomNumberToEachRoom[totalRoom] = room;
   }

   function getEachRoom(uint256 _index) public view returns () {
       return eachRoomNumberToEachRoom[totalRoom][_index];
   }
}

關注NESTED_ARRAYS_NOT_IMPLEMENTED,您將獲得有價值的資訊。

當期望返回值的函式時,您需要指定 return 語句的類型,因此您的getEachRoom函式需要指定它正在返回一個Room儲存在記憶體中的對象。所以getEachRoom應該是這樣的:

   function getEachRoom(uint256 _index) public view returns (Room memory) {
       return eachRoomNumberToEachRoom[totalRoom][_index];
   }

引用自:https://ethereum.stackexchange.com/questions/132415