Categorygithub.com/d5/tengo/v2
modulepackage
2.17.0
Repository: https://github.com/d5/tengo.git
Documentation: pkg.go.dev

# README

The Tengo Language

GoDoc test Go Report Card

Tengo is a small, dynamic, fast, secure script language for Go.

Tengo is fast and secure because it's compiled/executed as bytecode on stack-based VM that's written in native Go.

/* The Tengo Language */
fmt := import("fmt")

each := func(seq, fn) {
    for x in seq { fn(x) }
}

sum := func(init, seq) {
    each(seq, func(x) { init += x })
    return init
}

fmt.println(sum(0, [1, 2, 3]))   // "6"
fmt.println(sum("", [1, 2, 3]))  // "123"

Test this Tengo code in the Tengo Playground

Features

Benchmark

fib(35)fibt(35)Language (Type)
Tengo2,315ms3msTengo (VM)
go-lua4,028ms3msLua (VM)
GopherLua4,409ms3msLua (VM)
goja5,194ms4msJavaScript (VM)
starlark-go6,954ms3msStarlark (Interpreter)
gpython11,324ms4msPython (Interpreter)
Yaegi11,715ms10msYaegi (Interpreter)
otto48,539ms6msJavaScript (Interpreter)
Anko52,821ms6msAnko (Interpreter)
----
Go47ms2msGo (Native)
Lua756ms2msLua (Native)
Python1,907ms14msPython2 (Native)

* fib(35): Fibonacci(35)
* fibt(35): tail-call version of Fibonacci(35)
* Go does not read the source code from file, while all other cases do
* See here for commands/codes used

Quick Start

go get github.com/d5/tengo/v2

A simple Go example code that compiles/runs Tengo script code with some input/output values:

package main

import (
	"context"
	"fmt"

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

func main() {
	// create a new Script instance
	script := tengo.NewScript([]byte(
`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
})`))

	// 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"
}

Or, if you need to evaluate a simple expression, you can use Eval function instead:

res, err := tengo.Eval(ctx,
	`input ? "success" : "fail"`,
	map[string]interface{}{"input": 1})
if err != nil {
	panic(err)
}
fmt.Println(res) // "success"

References

# Packages

# Functions

CountObjects returns the number of objects that a given object o contains.
Eval compiles and executes given expr with params, and returns an evaluated value.
Format is like fmt.Sprintf but using Objects.
FormatInstructions returns string representation of bytecode instructions.
FromInterface will attempt to convert an interface{} v to a Tengo Object.
GetAllBuiltinFunctions returns all builtin function objects.
MakeInstruction returns a bytecode for an opcode and the operands.
NewCompiler creates a Compiler.
NewModuleMap creates a new module map.
NewScript creates a Script instance with an input script.
NewSymbolTable creates a SymbolTable.
NewVariable creates a Variable.
NewVM creates a VM.
ToBool will try to convert object o to bool value.
ToByteSlice will try to convert object o to []byte value.
ToFloat64 will try to convert object o to float64 value.
ToInt will try to convert object o to int value.
ToInt64 will try to convert object o to int64 value.
ToInterface attempts to convert an object o to an interface{} value.
ToRune will try to convert object o to rune value.
ToString will try to convert object o to string value.
ToTime will try to convert object o to time.Time value.

# Constants

GlobalsSize is the maximum number of global variables for a VM.
MaxFrames is the maximum number of function frames for a VM.
List of symbol scopes.
List of symbol scopes.
List of symbol scopes.
List of symbol scopes.
SourceFileExtDefault is the default extension for source files.
StackSize is the maximum stack size for a VM.

# Variables

ErrBytesLimit represents an error where the size of bytes value exceeds the limit.
ErrIndexOutOfBounds is an error where a given index is out of the bounds.
ErrInvalidIndexOnError represents an invalid index on error.
ErrInvalidIndexType represents an invalid index type.
ErrInvalidIndexValueType represents an invalid index value type.
ErrInvalidOperator represents an error for invalid operator usage.
ErrInvalidRangeStep is an error where the step parameter is less than or equal to 0 when using builtin range function.
ErrNotImplemented is an error where an Object has not implemented a required method.
ErrNotIndexable is an error where an Object is not indexable.
ErrNotIndexAssignable is an error where an Object is not index assignable.
ErrObjectAllocLimit is an objects allocation limit error.
ErrStackOverflow is a stack overflow error.
ErrStringLimit represents an error where the size of string value exceeds the limit.
ErrWrongNumArguments represents a wrong number of arguments error.
FalseValue represents a false value.
MaxBytesLen is the maximum length for bytes value.
MaxStringLen is the maximum byte-length for string value.
TrueValue represents a true value.
UndefinedValue represents an undefined value.

# Structs

Array represents an array of objects.
ArrayIterator is an iterator for an array.
Bool represents a boolean value.
BuiltinFunction represents a builtin function.
BuiltinModule is an importable module that's written in Go.
Bytecode is a compiled instructions and constants.
Bytes represents a byte array.
BytesIterator represents an iterator for a string.
Char represents a character value.
Compiled is a compiled instance of the user script.
CompiledFunction represents a compiled function.
Compiler compiles the AST into a bytecode.
CompilerError represents a compiler error.
ErrInvalidArgumentType represents an invalid argument value type error.
Error represents an error value.
Float represents a floating point number value.
ImmutableArray represents an immutable array of objects.
ImmutableMap represents an immutable map object.
Int represents an integer value.
Map represents a map of objects.
MapIterator represents an iterator for the map.
ModuleMap represents a set of named modules.
ObjectImpl represents a default Object Implementation.
ObjectPtr represents a free variable.
Script can simplify compilation and execution of embedded scripts.
SourceModule is an importable module that's written in Tengo.
String represents a string value.
StringIterator represents an iterator for a string.
Symbol represents a symbol in the symbol table.
SymbolTable represents a symbol table.
Time represents a time value.
Undefined represents an undefined value.
UserFunction represents a user function.
Variable is a user-defined variable for the script.
VM is a virtual machine that executes the bytecode compiled by Compiler.

# Interfaces

Importable interface represents importable module instance.
Iterator represents an iterator for underlying data type.
ModuleGetter enables implementing dynamic module loading.
Object represents an object in the VM.

# Type aliases

CallableFunc is a function signature for the callable functions.
SymbolScope represents a symbol scope.