gosh/doc/anko_syntax_guide.md

110 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# go-lang-anko 脚本语法指南
## 简介
`anko` 是一个用 Go 编写的轻量级脚本引擎,支持动态执行 Go 风格的脚本代码。它适用于需要嵌入脚本功能的 Go 应用程序。
## 基本语法
### 变量声明与赋值
```go
// 声明变量并赋值
x = 42
name = "anko"
// 多变量赋值
a, b = 1, 2
```
### 控制结构
#### if 语句
```go
if x > 0 {
println("x is positive")
} else {
println("x is non-positive")
}
```
#### for 循环
```go
// 类似 Go 的 for 循环
for i = 0; i < 10; i++ {
println(i)
}
// 类似 while 的循环
for x < 100 {
x *= 2
}
```
#### switch 语句
```go
switch x {
case 1:
println("one")
case 2:
println("two")
default:
println("unknown")
}
```
### 函数定义与调用
```go
// 定义函数
func add(a, b) {
return a + b
}
// 调用函数
result = add(3, 4)
```
### 内置函数和标准库
`anko` 支持部分 Go 标准库函数,例如:
```go
// 字符串操作
s = "hello"
println(len(s)) // 输出 5
// 数学函数
println(math.Pi)
```
### 错误处理
```go
// 使用 try-catch 捕获错误
try {
x = 1 / 0
} catch(err) {
println("Error:", err)
}
```
## 示例代码
### 计算斐波那契数列
```go
func fib(n) {
if n <= 1 {
return n
}
return fib(n-1) + fib(n-2)
}
println(fib(10)) // 输出 55
```
### 文件操作
```go
// 读取文件内容
content = file.Read("example.txt")
println(content)
```
## 注意事项
1. **性能**`anko` 是解释执行的,性能不如原生 Go 代码。
2. **安全性**:避免执行不可信的脚本代码。
3. **限制**:不支持 Go 的所有特性(如指针、接口等)。
4. **调试**:使用 `println``try-catch` 进行简单调试。