tengo icon indicating copy to clipboard operation
tengo copied to clipboard

how to return from the script (not function)

Open siff-duke opened this issue 5 years ago • 5 comments

How do you exit the script?

result = _fields["Addr"]
if result == undefined {
  return
}

I get the following error

Compile Error: return not allowed outside function

siff-duke avatar Dec 22 '20 04:12 siff-duke

You can use os.exit function from the standard library https://github.com/d5/tengo/blob/master/docs/stdlib-os.md#functions

geseq avatar Dec 22 '20 04:12 geseq

unfortunately, the scripts are user defined and we dont want to include the os library (security, etc).

I would be nice if it would allow it.

siff-duke avatar Dec 22 '20 04:12 siff-duke

Hi @siff-duke I had same requirement before, as a workaround I used runtime errors.

Example:

var ErrUserExit = errors.New("user exit")

func Example() {
  script := `
  result = _fields["Addr"]
  if result == undefined {
    exit()
  }
  `
  s := tengo.NewScript([]byte(script))
  err := s.Add("exit", &tengo.UserFunction{
    Name: "exit",
    Value: func(args ...tengo.Object) (tengo.Object, error) {
      return nil, ErrUserExit
    },
  })
  if err != nil {
    log.Fatal(err)
  }
  c, err := s.Compile()
  if err != nil {
    log.Fatal(err)
  }
  err = c.Run()
  if err != nil {
    if errors.Is(err, ErrUserExit) {
      // normal exit
    }
  }
}

ozanh avatar Dec 22 '20 11:12 ozanh

Maybe we should just add a new intrinsic function (e.g. exit).

d5 avatar Dec 22 '20 18:12 d5

my preference would be return but exit works.

siff-duke avatar Dec 22 '20 18:12 siff-duke