Embedding
Get up and running with Scriptling as an embedded scripting language in your Go application.
Installation
go get github.com/paularlott/scriptlingHello World
package main
import (
"fmt"
"github.com/paularlott/scriptling"
"github.com/paularlott/scriptling/stdlib"
)
func main() {
// Create interpreter
p := scriptling.New()
// Register standard libraries
stdlib.RegisterAll(p)
// Execute Scriptling code
_, err := p.Eval(`
print("Hello, World!")
`)
if err != nil {
fmt.Println("Error:", err)
}
}Variables and Functions
p := scriptling.New()
stdlib.RegisterAll(p)
result, err := p.Eval(`
# Variables
x = 42
name = "Alice"
numbers = [1, 2, 3]
# Functions
def greet(n):
return "Hello " + n
# Output
print(greet(name))
print("Sum:", x + len(numbers))
`)Variable Exchange
Pass data between Go and Scriptling. This complete example registers the requests extension library alongside the standard libraries:
package main
import (
"fmt"
"github.com/paularlott/scriptling"
"github.com/paularlott/scriptling/extlibs/requests"
"github.com/paularlott/scriptling/stdlib"
)
func main() {
p := scriptling.New()
stdlib.RegisterAll(p)
requests.Register(p)
if err := p.SetVar("api_base", "https://jsonplaceholder.typicode.com"); err != nil {
fmt.Println("Set variable:", err)
return
}
if err := p.SetVar("timeout", 10); err != nil {
fmt.Println("Set variable:", err)
return
}
_, err := p.Eval(`
import json
import requests
response = requests.get(api_base + "/users", timeout=timeout)
response.raise_for_status()
data = json.loads(response.text)
result = len(data)
`)
if err != nil {
fmt.Println("Script error:", err)
return
}
count, getErr := p.GetVarAsInt("result")
if getErr != nil {
fmt.Println("Result error:", getErr.Inspect())
return
}
fmt.Printf("Found %d users\n", count)
}This registers unrestricted outbound HTTP access. For untrusted scripts, pass a *netsecurity.Config to requests.Register and restrict the destinations scripts may contact; see Library Registration.
Registering Libraries
Libraries are not available to scripts unless you register them. The standard libraries have no filesystem, network, process or host access, so they are safe to give any script; register them all with a single call:
import "github.com/paularlott/scriptling/stdlib"
// Register all standard libraries (json, math, re, time, etc.)
stdlib.RegisterAll(p)Extension libraries (requests, os, yaml, subprocess, the scriptling.* libraries and so on) each live in their own Go package and are registered individually, so your binary links only the ones you use. See Library Registration for the complete list and signatures.
Next Steps
- Go Integration Basics - Complete guide to interpreters, variables, and functions
- Native API - Direct object-level control
- Builder API - Type-safe, cleaner syntax
- Libraries - Library usage and registration reference
- Error Handling - try/except, raise, and returning SystemExit to the host
- Security Guide - Security best practices for embedding