简体   繁体   中英

Can I call a function inside a function solidity?

I have a function in my contract that take 2 numbers and give a random number between those 2. Can I call this function inside some others functions in the same contract?

Something like:

function point(min, max) public view returns (uint256) {
    return /* A number betwwen "min" and "max" */;
}

function generateSVG() public pure returns (string memory) {
   .
   .
   .
    svg = string(abi.encodePacked(svg, "stroke-width='" , point(1, 5) , "' "));
   .
   .
   .
}

Thank you:D

Short answer: sometimes.

Long answer:

In solidity, we specify the visibility of functions and state variables. There are 4 types of visibility:

  • Internal
  • External
  • Public
  • Private

Unless defined explicitly, visibility defaults to internal .

Internal

A function/state variable is only visible to contracts that contains it, or inherits a contract that contains it

External

Can only be called by other contracts

Public

Any contract, whether it contains the code or not, can call

Private

Only the contract that declares it can call, not the ones that inherit it.

Beware, regarding randomness

There is no true randomness in ethereum. You can either create pseudo-random values with blockhash/block height or you can use an oracle that provides true randomness, like Chainlik

yes, you can call it will work unless you defined it as either public or private(in case you want to call the function within the same contract and restrict to inherited contracts) or internal. an example is shown below.

`// SPDX-License-Identifier: MIT pragma solidity ^0.8.5;

contract FunctionCall {

uint public addition = add(1,2);
uint public product = multiply(add(2,3),add(2,1));

function add(uint a,uint b)public pure returns(uint output){
    output = a+b;
}

function multiply(uint a,uint b)public pure returns(uint){
    return a*b;
}

} `

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM