-
I would like to export variable which could be then updated by the evaluated script. I tried the following code but without luck: package main
import (
"fmt"
"reflect"
"github.com/traefik/yaegi/interp"
)
func main() {
var variable int // this is a variable which I would like to update inside evaluated script
interpreter := interp.New(interp.Options{})
err := interpreter.Use(interp.Exports{
"main/main": map[string]reflect.Value{
"variable": reflect.ValueOf(&variable).Elem(),
},
})
if err != nil {
panic(err)
}
if _, err = interpreter.Eval(`import . "main"`); err != nil {
panic(err)
}
var res any
res, err = interpreter.Eval("variable=3")
if err != nil {
panic(err)
}
fmt.Println(res)
fmt.Println(variable) // this should return 3
} Trying to evaluate
Is there any other way to do that? |
Beta Was this translation helpful? Give feedback.
Answered by
elgopher
Aug 11, 2023
Replies: 2 comments
-
I figure it out myself. Here is the working version: package main
import (
"fmt"
"reflect"
"github.com/traefik/yaegi/interp"
)
func main() {
var variable int // this is a variable which I would like to update inside evaluated script
interpreter := interp.New(interp.Options{})
err := interpreter.Use(interp.Exports{
"main/main": map[string]reflect.Value{
"variable": reflect.ValueOf(&variable), // pass the pointer to variable
},
})
if err != nil {
panic(err)
}
if _, err = interpreter.Eval(`import . "main"`); err != nil {
panic(err)
}
var res any
res, err = interpreter.Eval("*variable=3") // variable name must be prepended with "*"
if err != nil {
panic(err)
}
fmt.Println(res)
fmt.Println(variable)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
elgopher
-
Your solution works, but in my opinion the fact that your first attempt doesn't work is a bug. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I figure it out myself. Here is the working version: