vety-language/doc/02_control_flow.md

131 lines
2.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# Vety语言控制流程
## 1. 条件语句
### 1.1 if-else语句
Vety使用`if`和`else`关键字进行条件控制:
```vety
let score: i32 = 85
if (score >= 90) {
print("优秀")
} else if (score >= 80) {
print("良好")
} else if (score >= 60) {
print("及格")
} else {
print("不及格")
}
```
条件表达式必须是布尔类型Vety不会进行隐式的真值转换。
### 1.2 条件表达式的组合
可以使用逻辑运算符组合多个条件:
```vety
let age: i32 = 25
let has_ticket: bool = true
if (age >= 18 && has_ticket) {
print("允许入场")
} else {
print("不允许入场")
}
```
## 2. 循环语句
### 2.1 while循环
`while`循环在条件为真时重复执行代码块:
```vety
let count: i32 = 0
while (count < 5) {
print(count)
count = count + 1
}
```
### 2.2 for循环
Vety的`for`循环支持遍历数组和范围:
```vety
// 遍历数组
let numbers: array = [1, 2, 3, 4, 5]
for (let i: i32 = 0; i < numbers.len; i++) {
print(numbers[i])
}
```
## 3. 循环控制
### 3.1 break语句
使用`break`语句可以提前退出循环:
```vety
let i: i32 = 0
while (true) {
if (i >= 5) {
break
}
print(i)
i = i + 1
}
```
### 3.2 continue语句
使用`continue`语句可以跳过当前循环的剩余部分,直接进入下一次循环:
```vety
for (let i: i32 = 0; i < 10; i++) {
if (i % 2 == 0) {
continue // 跳过偶数
}
print(i) // 只打印奇数
}
```
## 4. 错误处理
### 4.1 try-catch语句
Vety使用`try`和`catch`进行错误处理:
```vety
try {
// 可能产生错误的代码
let result = dangerous_operation()
} catch(e) {
// 错误处理代码
print("操作失败")
}
```
### 4.2 错误传播
函数可以使用返回值来传播错误:
```vety
func divide(a: i32, b: i32): i32 {
if b == 0 {
throw "除数不能为零"
}
return a / b
}
try {
let result = divide(10, 0)
} catch(e) {
print("除法运算失败")
}
```