1

I wanted to access (update/get) data from a mapping in another contract. Is it possible to access the mapping variables without writing a function to read/write. I looked at (here) but still little unclear on the approach.

I am getting an error "Indexed expression has to be a type, mapping, array at the line - "myData.contractsMap[_name].push(_value)"

Any suggestions? Thanks,

pragma solidity ^0.4.15;

contract Data {

    mapping (bytes32 => uint[])  public contractsMap;

}

contract ContractCreator {

    Data myData;
    uint[] myValueList;

    event Log(bytes32, uint);

    function ContractCreator() public {

        myData = new Data();
    }

    function setElements (bytes32 _name, uint _value) public {

        myData.contractsMap[_name].push(_value); //ERROR
    }

    function getElements (bytes32 _name) public {

       myValueList = myData.contractsMap[_name];
       for (uint i = 0; i < myValueList.length; i++) {
           Log(_name, myValueList[i]);
       }
    }
}
1

Sorry, but you are currently not allowed to access mappings of type (bytes32 => uint[]) in other contracts. You have to create the getters/setters in your Data contract and modify/access the mappings through these getters/setters in your ContractCreator contract.

| improve this answer | |
2

mappings are private by default. like the poster above said, you'll need to have setters and getters in order for it to be accessible.

contract ContractFoo {
  mapping (address=>uint) somemapping; //not accessible unless there is a getter

  function getMapping(address _address) public constant returns (uint) {
    return somemapping[addr]
  }
}

here's a fiddle: https://ethfiddle.com/D0H5CVFT1B

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.