Skip to content

Example to make function call and retrieve result. #468

@prasad83

Description

@prasad83

I found a way to invoke tengo script function from Go and retrieve result.
Documenting it for others.

package main

import (
	"fmt"
	"strings"
	"time"

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

func main() {

	// Tengo source which has function defined
	source := `
		greetUser := func(name) {
			return ["Hello", name]
		}
	`

	// How to invoke the function and collect the return value securely.

	// Define random result variable (overcomes collision with source variables).
	resultVarName := fmt.Sprintf("__result_%d", time.Now().UnixNano())

	// Target method to call with arguments
	methodName := "greetUser"
	methodArgs := []string{`"Yourname"`}

	// Rebuild source
	fullSource := source + fmt.Sprintf("\n%s := %s(%s)",
		resultVarName, methodName, strings.Join(methodArgs, ","))

	script := tengo.NewScript([]byte(fullSource))

	if compiled, err := script.Compile(); err != nil {
		panic(err)
	} else {
		if err = compiled.Run(); err != nil {
			panic(err)
		}
		result := compiled.Get(resultVarName)
		fmt.Printf("%#v", result.Value())
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions