Try the following:
function getUsersCount() public constant returns(uint) {
return users.length;
}
function getUser(uint index) public constant returns(uint, string, address) {
return (users[index].idNum, users[index].name, users[index].userAddress);
}
You should then be able use the statements:
> var numberOfUsers = contract.usersCount();
undefined
> numberOfUsers
5
> var user0 = contract.users(0)
[123, "User 123", "0xbeefee3ad17cd9aca6fd5343a53a513685c7e0ed"]
> var user1 = contract.getUser(1)
[234, "User 234", "0xbeefee3ad17cd9aca6fd5343a53a513685c7e0ed"]
> var lastUser = arrayStruct.users(numberOfUsers-1)
undefined
> lastUser
[567, "User 567", "0xbeefee3ad17cd9aca6fd5343a53a513685c7e0ed"]
And responding to the comment by Nikhil M
, the statement below always returns 0 for me. I don't know if it is a design feature or a bug.
> var users = contract.users.length
undefined
> users
0
Gas Cost
The call to contract.usersCount()
, contract.users(x)
and contract.getUser()
don't change the blockchain data and don't cost gas. From Greeter,
Run the Greeter
In order to call your bot, just type the following command in your terminal:
greeter.greet();
Since this call changes nothing on the blockchain, it returns instantly and without any gas cost. You should see it return your greeting:
This is the contract code that I used:
contract ArrayStruct {
struct User {
uint idNum;
string name;
address userAddress;
}
User[] public users;
function addUser(uint _idNum, string _name, address _userAddress) public returns(uint) {
users.length++;
users[users.length-1].idNum = _idNum;
users[users.length-1].name = _name;
users[users.length-1].userAddress = _userAddress;
return users.length;
}
function getUsersCount() public constant returns(uint) {
return users.length;
}
function getUser(uint index) public constant returns(uint, string, address) {
return (users[index].idNum, users[index].name, users[index].userAddress);
}
}
You will have to pay the gas for inserting the contract into the blockchain as shown by the gas: 1000000
field in the following statement:
var contract = arrayStructContract.new({
from:web3.eth.accounts[0],
data: arrayStructCompiled.ArrayStruct.code,
gas: 1000000
}, function(e, contract) {
if (!e) {
if(!contract.address) {
console.log("Contract transaction send: TransactionHash: " +
contract.transactionHash + " waiting to be mined...");
} else {
console.log("Contract mined! Address: " + contract.address);
console.log(contract);
}
}
})
And you will have to pay the gas when you change the blockchain data, as shown by the gas: 500000
in the following statements:
contract.addUser(123, "User 123", eth.accounts[0], {
from:web3.eth.accounts[0],
data: arrayStructCompiled.ArrayStruct.code,
gas: 500000
});
contract.addUser(234, "User 234", eth.accounts[0], {
from:web3.eth.accounts[0],
data: arrayStructCompiled.ArrayStruct.code,
gas: 500000
});
var users = contract.users.length
in your.js
file,