尝试访问 Hardhat 中的 Solidity 结构数组时出错无效操作码

Error invalid opcode trying to access Solidity array of structs in Hardhat

我的 Solidity 代码中有以下结构和数组:

    struct Character {
        int256 strength;
        uint256 dexterity;
        uint256 constitution;
       ....
    }

    Character[] public characters;

我的 Hardhat 测试中有以下行试图访问该数组的成员:

const character = await contract.characters(0)

然后我收到以下错误:

 Error: VM Exception while processing transaction: invalid opcode
      at Contract.characters 

访问此结构数组成员的正确方法是什么?

正如问题评论中指出的那样,调用 characters(0) 函数时 characters 数组为空。

Solidity 为 public 数组自动生成 getter 函数,允许使用其索引访问数组的项目。

当您尝试访问越界的索引时,EVM 会抛出异常。