Skip to content

How to update exported variable inside evaluated script? #1581

Closed Answered by elgopher
elgopher asked this question in Q&A
Discussion options

You must be logged in to vote

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)
	}
	

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by elgopher
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants