Search code examples
ethereumcontractsolidity

Getting the length of public array variable (getter)


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;
    }
}

Solution

  • 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.