Skip to content

Commit

Permalink
starlark: add example of Starlark built-in function in Go (google#217)
Browse files Browse the repository at this point in the history
  • Loading branch information
adonovan authored Jul 2, 2019
1 parent 6ddc71c commit dbbb761
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion starlark/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,35 @@ import (
func ExampleExecFile() {
const data = `
print(greeting + ", world")
print(repeat("one"))
print(repeat("mur", 2))
squares = [x*x for x in range(10)]
`

// repeat(str, n=1) is a Go function called from Starlark.
// It behaves like the 'string * int' operation.
repeat := func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var s string
var n int = 1
if err := starlark.UnpackArgs(b.Name(), args, kwargs, "s", &s, "n?", &n); err != nil {
return nil, err
}
return starlark.String(strings.Repeat(s, n)), nil
}

// The Thread defines the behavior of the built-in 'print' function.
thread := &starlark.Thread{
Name: "example",
Print: func(_ *starlark.Thread, msg string) { fmt.Println(msg) },
}

// This dictionary defines the pre-declared environment.
predeclared := starlark.StringDict{
"greeting": starlark.String("hello"),
"repeat": starlark.NewBuiltin("repeat", repeat),
}

// Execute a program.
globals, err := starlark.ExecFile(thread, "apparent/filename.star", data, predeclared)
if err != nil {
if evalErr, ok := err.(*starlark.EvalError); ok {
Expand All @@ -51,6 +69,8 @@ squares = [x*x for x in range(10)]

// Output:
// hello, world
// one
// murmur
//
// Globals:
// squares (list) = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Expand Down

0 comments on commit dbbb761

Please sign in to comment.