vety-language/doc/02_control_flow.md

2.0 KiB
Raw Permalink Blame History

Vety语言控制流程

1. 条件语句

1.1 if-else语句

Vety使用ifelse关键字进行条件控制:

let score: i32 = 85

if (score >= 90) {
    print("优秀")
} else if (score >= 80) {
    print("良好")
} else if (score >= 60) {
    print("及格")
} else {
    print("不及格")
}

条件表达式必须是布尔类型Vety不会进行隐式的真值转换。

1.2 条件表达式的组合

可以使用逻辑运算符组合多个条件:

let age: i32 = 25
let has_ticket: bool = true

if (age >= 18 && has_ticket) {
    print("允许入场")
} else {
    print("不允许入场")
}

2. 循环语句

2.1 while循环

while循环在条件为真时重复执行代码块:

let count: i32 = 0

while (count < 5) {
    print(count)
    count = count + 1
}

2.2 for循环

Vety的for循环支持遍历数组和范围:

// 遍历数组
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语句可以提前退出循环:

let i: i32 = 0
while (true) {
    if (i >= 5) {
        break
    }
    print(i)
    i = i + 1
}

3.2 continue语句

使用continue语句可以跳过当前循环的剩余部分,直接进入下一次循环:

for (let i: i32 = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue  // 跳过偶数
    }
    print(i)     // 只打印奇数
}

4. 错误处理

4.1 try-catch语句

Vety使用trycatch进行错误处理:

try {
    // 可能产生错误的代码
    let result = dangerous_operation()
} catch(e) {
    // 错误处理代码
    print("操作失败")
}

4.2 错误传播

函数可以使用返回值来传播错误:

func divide(a: i32, b: i32): i32 {
    if b == 0 {
        throw "除数不能为零"
    }
    return a / b
}

try {
    let result = divide(10, 0)
} catch(e) {
    print("除法运算失败")
}