5

I am trying to get the length of array from another contact. How?

contract Lottery {
    unint[] public bets;
}

contract CheckLottery {
    function CheckLottery() {
        Lottery.bets.length;
    }
}
RFV
  • 831
  • 8
  • 22

1 Answers1

8

You have to expose the length you want as a function return value in the source contract.

The calling contract will need the ABI and contract address, which is handled via the state var and constructor below.

pragma solidity ^0.4.8;

contract Lottery {

    uint[] public bets;

    function getBetCount()
        public 
        constant
        returns(uint betCount)
    {
        return bets.length;
    }
}

contract CheckLottery {

    Lottery l;

    function CheckLottery(address lottery) {
        l = Lottery(lottery);
    }

    function checkLottery() 
        public
        constant
        returns(uint count) 
    {
        return l.getBetCount();
    }
}

Hope it helps.

Rob Hitchens
  • 1,049
  • 10
  • 14
  • Yes it seems that, that property (method) is not exposed by default. – RFV Mar 26 '17 at 08:21
  • 1
    Just wondering why the `getBetCount()` has 6 lines? I don't have VR 360 space dome code environment, I much prefer preserve screen real estate... – Mars Robertson Jul 13 '18 at 18:28
  • Do we know why we have to use a `getter` for arrays but for primatives like `uint256` we can just call them like in this: https://ethereum.stackexchange.com/questions/38317/access-to-public-variable-from-other-contract – Patrick Collins Feb 15 '21 at 19:31
  • If I understand the question ... You can use the "free" getter for `public` array _element_ but there is no "free" getter for the `length` _property_ of the array or the entire array. Passing entire arrays around should be avoided unless you really understand the implications. – Rob Hitchens Feb 16 '21 at 08:22