example_test.go 674 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package tengo_test
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/d5/tengo/v2"
  6. )
  7. func Example() {
  8. // Tengo script code
  9. src := `
  10. each := func(seq, fn) {
  11. for x in seq { fn(x) }
  12. }
  13. sum := 0
  14. mul := 1
  15. each([a, b, c, d], func(x) {
  16. sum += x
  17. mul *= x
  18. })`
  19. // create a new Script instance
  20. script := tengo.NewScript([]byte(src))
  21. // set values
  22. _ = script.Add("a", 1)
  23. _ = script.Add("b", 9)
  24. _ = script.Add("c", 8)
  25. _ = script.Add("d", 4)
  26. // run the script
  27. compiled, err := script.RunContext(context.Background())
  28. if err != nil {
  29. panic(err)
  30. }
  31. // retrieve values
  32. sum := compiled.Get("sum")
  33. mul := compiled.Get("mul")
  34. fmt.Println(sum, mul)
  35. // Output:
  36. // 22 288
  37. }