2

inside a Solidity contract there is a declaration as follows:

contract Lottery is VRFConsumerBase, Ownable {
address payable[] public players;
...
...

elsewhere in the same contract,there is a an assignment as follows:

....
....
recentWinner = players[someIndex];
....
....

} 

the deploy.py Python script is used to deploy the contract. the function deploying the contract is:

def deploy_lottery():
      Lottery.deploy(....)
....
....

After deployment and doing other stuff... the contract's recentWinner variable is accessed from python script using parenthesis as follows:

def end_lottery():
      print(f"{lottery.recentWinner()} is the winner!")
  

My rather basic question is, why are parenthesis used? recentWinner is not a function that was defined in the Lottery contract. If I ran the script without the paranthesis, I get the following output.

<ContractCall 'recentWinner()'> is the winner!
Terminating local RPC client...

so it seems like the paranthesis is necessary. can somebody explain what is going on please? why should I treat this variable like a function in order to retrieve its value? if you can also point me to some related posts/reading material that would be much appreciated. thank you!

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
maskara
  • 329
  • 1
  • 2
  • 12
  • I would inspect the contents of `players` in the first place. Does it contain strings, or callable objects/functions? – joanis Jan 28 '22 at 01:01

1 Answers1

4

EVM does not have public variables, only public accessor functions.

Behind the scenes, the Solidity compiler generates a function called recentWinner() for you. This is called accessor or getter function. Unlike in Java etc. languages there is no get prefix for the function.

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • 1
    Thank you! this answers my question ! the the lik to the article is also very helpful – maskara Jan 28 '22 at 04:52
  • Please press the check tick button on the answer if it is a correct answer. Welcome to StackOverflow :) – Mikko Ohtamaa Jan 28 '22 at 08:53
  • 1
    Thank you Mikko ! – maskara Jan 28 '22 at 15:23
  • while the recentWinner() seems to work during testing, the players(4) does not work. _players(4) is how I'm trying to retrieve the 5th element of the array **players**_ . `assert lottery.recentWinner() == lottery.players(5) ` **players** and **recentWinner** is defined as follows inside the **Lottery** contract as follows: `address payable[] public players;` Is this the correct syntax for using a getter function for arrays ? Thanks ! – maskara Jan 28 '22 at 22:50
  • AFAIK there is no accessor function for arrays and you need to write getPlayer(idx) yourself. But I might be wrong, Solidity has changed a lot. I suggest you refer to the documentation. – Mikko Ohtamaa Jan 29 '22 at 11:17
  • link doesn't work – Yves Boutellier Jun 17 '22 at 03:55