Getting the length of public array variable (getter)
Asked Answered
F

1

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;
    }
}
Fifteen answered 25/3, 2017 at 11:54 Comment(0)
B
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.

Bistort answered 25/3, 2017 at 18:5 Comment(4)
Yes it seems that, that property (method) is not exposed by default.Fifteen
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...Forego
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: ethereum.stackexchange.com/questions/38317/…Ideogram
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.Bistort

© 2022 - 2024 — McMap. All rights reserved.