From dbbb761c3745a4e148fe69872db04e9663ff61cb Mon Sep 17 00:00:00 2001 From: alandonovan Date: Tue, 2 Jul 2019 15:30:00 -0400 Subject: starlark: add example of Starlark built-in function in Go (#217) Fixes #216 --- starlark/example_test.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'starlark') 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] -- cgit v1.2.3