aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoralandonovan <adonovan@google.com>2019-07-02 15:30:00 -0400
committerGitHub <noreply@github.com>2019-07-02 15:30:00 -0400
commitdbbb761c3745a4e148fe69872db04e9663ff61cb (patch)
treec6f829758b03c805eb4c16384cc641d5165e236a
parent6ddc71c0ba77217b518c586dc8589d627c92ebfb (diff)
downloadstarlark-go-dbbb761c3745a4e148fe69872db04e9663ff61cb.tar.gz
starlark: add example of Starlark built-in function in Go (#217)
Fixes #216
-rw-r--r--starlark/example_test.go22
1 files changed, 21 insertions, 1 deletions
diff --git a/starlark/example_test.go b/starlark/example_test.go
index 727097b..4bd0c74 100644
--- a/starlark/example_test.go
+++ b/starlark/example_test.go
@@ -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 {
@@ -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]