DAY 8
1
Blockchain

## 函式

### 有回傳值的函式

``````function alert(string memory text) public pure returns (string memory) {
return text;
}
``````

### 回傳多值的函式

``````function show(string memory text) public pure returns (string memory, string memory) {
}
``````

### 函式呼叫函式

``````function test() public pure returns (string memory) {
return sayHello();
}

function sayHello() private pure returns (string memory) {
return "Hello";
}
``````

## 條件敘述

### if...else

``````function test() public pure returns (string memory) {
uint num = 2;
if (num > 1) {
return "HelloWorld";
} else {
return "HAHA";
}
}
``````

### 三元運算子

``````function test4() public pure returns (uint) {
uint num = 20;
num = (num == 20)? 1 : 3;
return num;
}
``````

## 迴圈敘述

`for``while``do...while` 可以使用。

### for

``````function test() public pure returns (uint) {
uint num = 0;
for (uint i = 0; i < 10; i++) {
num++;
}
return num;
}
``````

### while

``````function test() public pure returns (uint) {
uint num = 0;
while(num < 10) {
num++;
}
return num;
}
``````

### do...while

``````function test() public pure returns (uint) {
uint num = 0;
do {
num++;
} while(num < 10);
return num;
}
``````

## 錯誤處理

### require

``````const example = (isFalse = false) => {
if (isFalse) {
return;
}
console.log('Hello'); //不會執行
}
``````

`require` 範例，寫在修飾詞中，並判斷是否為合約部署者：

``````pragma solidity ^0.5.0;

constract Permission {

require(msg.sender == admin, "You don't have permission.");
_; //要加這個
}

constructor() {
}

}
``````

### revert

`require` 十分接近但沒有條件判斷，當呼叫時會歸還剩餘的 Gas 並回復合約狀態。

``````function test() public pure returns (string memory) {
uint num = 0;
if (num != 1) {
resvert("is false");
}
return "HelloWorld";
}
``````

### assert

`require` 一樣做判斷，但當條件不成立時，會將 Gas 全數消耗，不會返回任何的 Gas ，並回復合約狀態。通常用來處理較嚴重的錯誤，如：程式 bug ，為最不該被經常使用到的錯誤處理。

``````function test() public pure returns (string memory) {
uint num = 0;
assert(num != 1); //基本上不可能發生，除非程式錯誤
return "HelloWorld";
}
``````

## 參考資料

Solidity 中Require(), Assert(), Revert()的用法和區別