动态 sprintf_Go 语言实现的小型、动态、快速、安全的脚本语言

关注公众号 “OpenSourceDaily” ,每天推荐给你优秀开源项目

今天为 Go 语言爱好者推荐一个脚本语言:Tengo,这是用 Go 语言实现的小型,动态,快速,安全的脚本语言。项目地址:https://github.com/d5/tengo,目前 Star 数:1.7k+。

Tengo 既快速又安全,因为它是用 native Go 编写的基于堆栈的 VM 上作为字节码编译/执行的。

特性

该语言的特性如下:

  • 简单易读的语法
    • 带类型强制的动态输入
    • 高阶函数和闭包
    • 不变值
  • 可安全嵌入和扩展
  • 用 native Go 编写的编译器/运行时(无外部 deps 或 cgo)
  • 可执行为独立语言或 REPL
  • 案例:规则引擎,状态机,数据管道,翻译器(如 tengo 到 lua)

性能如何呢?

904ac8d649d5ade1ee1471bb958af799.png

使用

Tengo 支持几种使用方式。

1)作为 Go 包,嵌入 Go 中使用,比如:

package main

import (
 "context"
 "fmt"

 "github.com/d5/tengo/v2"
)

func main() {
 // Tengo script code
 src := `
each := func(seq, fn) {
    for x in seq { fn(x) }
}
sum := 0
mul := 1
each([a, b, c, d], func(x) {
 sum += x
 mul *= x
})`

 // create a new Script instance
 script := tengo.NewScript([]byte(src))

 // set values
 _ = script.Add("a", 1)
 _ = script.Add("b", 9)
 _ = script.Add("c", 8)
 _ = script.Add("d", 4)

 // run the script
 compiled, err := script.RunContext(context.Background())
 if err != nil {
  panic(err)
 }

 // retrieve values
 sum := compiled.Get("sum")
 mul := compiled.Get("mul")
 fmt.Println(sum, mul) // "22 288"
}

编译运行使用 Go 来处理。需要按照 Tengo:

go get github.com/d5/tengo/v2

2)作为独立脚本使用

先安装 Tengo CLI:

go get github.com/d5/tengo/cmd/tengo

写下如下脚本:

fmt := import("fmt")
// 注意 p 是小写的
fmt.println("Hello Tengo!")

保存为:hello.tengo,之后执行如下命令:

tengo hello.tengo

输出:

Hello Tengo!

3)类似 Python,REPL 方式运行

很简单,输入 tengo 回车,然后交互式输入:

>> fmt := import("fmt")
{printf: , println: , sprintf: , print: , __module_name__: "fmt"}
>> fmt.println("Hello Tengo!")
Hello Tengo!
>>

相关文档

目前官方提供了如下文档,通过这些文档可以看到该脚本语言支持的功能。

  • 语言语法:https://github.com/d5/tengo/blob/master/docs/tutorial.md
  • 对象类型:https://github.com/d5/tengo/blob/master/docs/objects.md
  • 运行时类型:https://github.com/d5/tengo/blob/master/docs/runtime-types.md
  • 操作符:https://github.com/d5/tengo/blob/master/docs/operators.md
  • 内置函数:https://github.com/d5/tengo/blob/master/docs/builtins.md
  • 互通性:https://github.com/d5/tengo/blob/master/docs/interoperability.md
  • Tengo 命令行:https://github.com/d5/tengo/blob/master/docs/tengo-cli.md
  • 标准库:https://github.com/d5/tengo/blob/master/docs/stdlib.md

另外还提供了 VSCode 和 Atom 的语法高亮插件。

目前标准库不多,只有如下几个:

d35da7c450e3443f63f5d2dc5ddb2d78.png

在线 Playground

官方还提供了在线试验的 Playground:https://tengolang.com,有兴趣的可以试试!

文末「阅读原文」可直达项目首页。

今天的项目大家觉得怎么样吗?如果你喜欢,请在文章底部留言、点赞或关注转发,你的支持就是我持续更新的最大动力!

推荐阅读

  • 4月份Github上最热门的开源项目


OpenSourceDaily - 送给爱开源的你

aeea10366b21478a89e61d0e4e29bbaa.png

Git · GitHub · GitLab · Gitee

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值