带参modifire

modifire还可以带参数,如下面的例子,模拟了游戏中的升级操作。如果玩家等级达到2级,就可以修改名字。如果玩家等级达到10级,就可以修改DNA。
通过带参数的modifire实现对于代码的封装。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pragma solidity^0.4.23;

contract  modifiererParam{
   uint public level = 9;
   string public name;
   uint public DNA;

   modifier controlLevel(uint _needlevel){
       require(level>_needlevel);
       _;
   }

   //修改名字
   function changeName(string _name) public controlLevel(2){
       name = _name;
   }

   //修改DNA
     function changeDNA(uint _dna) public controlLevel(10){
       DNA = _dna;
   }
}

通过上面的例子,我们能够看到带参数的modifire的使用方法。首先在modifire中添加参数。接着在函数定义中,在修饰符与return返回值之间加上controlLevel(传递的参数).

例如,当调用changeName函数执行的语句为:

1
2
require(level>2);
name = _name;

例如,当调用changeDNA函数执行的语句为:

1
2
require(level>10);
name = _name;

多重modifire

函数可以有多个modifire,这种情况要相对复杂得多。
我们从下面的例子,来讲解多重modifire的执行过程。

案例1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
contract  mulmodifiererDeep{
   uint public a = 0;

   modifier mod1{
       a = 1;
       _;
       a = 2;
   }

   function test() public  mod1{

       a = 100;
   }

}

下面的例子中,当执行test方法后,状态变量a的值会变为2. 我们提到过,modifire中的下划线指代了函数中的所有语句。
所以执行流程为
a = 1 a = 100 a = 2

案例2

下面的例子中,使用了多重的modire。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
contract  mulmodifiererDeep2{
   uint public a = 0;

   modifier mod1{
       a = 1;
       _;
       a = 2;
   }

    modifier mod2{
       a = 3;
       _;
       a = 4;
   }

   function test() public  mod1 mod2{
       a = 100;
   }
}

在上面的例子中test函数使用了modifire:mod1、mod2
嵌套规则为,首先函数中的a = 100嵌套到mod2的_中。整个语句变为了
a = 3; a = 100; a = 4;
接下来,将上面的语句添加到mod1的下划线中,所以整个执行语句变为了

1
2
3
4
5
a = 1;
a = 3;
a = 100;
a = 4;
a = 2;

最后执行结果为 a = 2。

案例3

多重modifire的顺序非常的重要的。
下面的例子,和案例2相同但是修改了mod1与mod2在函数中的顺序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
contract  mulmodifiererDeep2{
   uint public a = 0;

   modifier mod1{
       a = 1;
       _;
       a = 2;
   }

    modifier mod2{
       a = 3;
       _;
       a = 4;
   }

   function test() public  mod2 mod1{
       a = 100;
   }
}

在上面的例子中test函数使用了modifire:mod2、mod1
嵌套规则为,首先函数中的a = 100嵌套到mod1的_中。整个语句变为了
a = 1; a = 100; a = 2;
接下来,将上面的语句添加到mod1的下划线中,所以整个执行语句变为了

1
2
3
4
5
a = 3;
a = 1;
a = 100;
a = 2;
a = 4;

最后执行结果为 a = 4。

solidity智能合约[33]-modifire-deep_区块链