简体   繁体   English

我可以在 function 实体中调用 function 吗?

[英]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?我的合同中有一个 function,它接受 2 个数字并在这两个数字之间给出一个随机数。我可以在同一个合同中的其他一些函数中调用这个 function 吗?

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谢谢:D

Short answer: sometimes.简短的回答:有时。

Long answer:长答案:

In solidity, we specify the visibility of functions and state variables.在 solidity 中,我们指定了函数和 state 个变量的可见性。 There are 4 types of visibility:有 4 种类型的可见性:

  • Internal内部的
  • External外部的
  • Public民众
  • Private私人的

Unless defined explicitly, visibility defaults to internal .除非明确定义,否则可见性默认为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您可以使用块哈希/块高度创建伪随机值,也可以使用提供真正随机性的 oracle,例如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.是的,除非您将其定义为公共或私有(如果您想在同一合同中调用 function 并限制为继承的合同)或内部,否则您可以调用它将起作用。 an example is shown below.一个例子如下所示。

`// SPDX-License-Identifier: MIT pragma solidity ^0.8.5; `// 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;
}

} ` }`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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