qri-io / starlib

qri's standard library for starlark
MIT License
116 stars 29 forks source link

fix: add support for marshalling and unmarshalling bytes #173

Open HarikrishnanBalagopal opened 1 year ago

HarikrishnanBalagopal commented 1 year ago

fixes #172

def fibonacci(n):
    res = list(range(n))
    for i in res[2:]:
        res[i] = res[i-2] + res[i-1]
    return bytes(res)

print(fibonacci(4))
package main

import (
    "fmt"

    "github.com/qri-io/starlib/util"
    "go.starlark.net/starlark"
)

func main() {
    // Execute Starlark program in a file.
    thread := &starlark.Thread{Name: "my thread"}
    globals, err := starlark.ExecFile(thread, "fibonacci.star", nil, nil)
    if err != nil {
        panic(err)
    }

    // Retrieve a module global.
    fibonacci := globals["fibonacci"]

    // Call Starlark function from Go.
    v, err := starlark.Call(thread, fibonacci, starlark.Tuple{starlark.MakeInt(10)}, nil)
    if err != nil {
        panic(err)
    }
    vI, err := util.Unmarshal(v)
    if err != nil {
        panic(err)
    }
    fmt.Printf("fibonacci(10) = %+v\n", vI) // fibonacci(10) = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
}
$ go run main.go 

errbadtype: bytes
panic: unrecognized starlark type: bytes

goroutine 1 [running]:
main.main()
    /Users/user/Desktop/test-star/main.go:28 +0x185
exit status 2
$ echo 'after replacing with my branch in go.mod'
$ go mod tidy
go: downloading github.com/HarikrishnanBalagopal/starlib v0.5.0-alpha.0
$ go run main.go 

fibonacci(10) = [0 1 1 2 3 5 8 13 21 34]