github.com/robertkrimen/otto@v0.2.1/documentation_test.go (about)

     1  package otto
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  func ExampleSynopsis() { //nolint: govet
     8  	vm := New()
     9  	vm.Run(`
    10          abc = 2 + 2;
    11          console.log("The value of abc is " + abc); // 4
    12      `)
    13  
    14  	value, _ := vm.Get("abc")
    15  	{
    16  		value, _ := value.ToInteger()
    17  		fmt.Println(value)
    18  	}
    19  
    20  	vm.Set("def", 11)
    21  	vm.Run(`
    22          console.log("The value of def is " + def);
    23      `)
    24  
    25  	vm.Set("xyzzy", "Nothing happens.")
    26  	vm.Run(`
    27          console.log(xyzzy.length);
    28      `)
    29  
    30  	value, _ = vm.Run("xyzzy.length")
    31  	{
    32  		value, _ := value.ToInteger()
    33  		fmt.Println(value)
    34  	}
    35  
    36  	value, err := vm.Run("abcdefghijlmnopqrstuvwxyz.length")
    37  	fmt.Println(value)
    38  	fmt.Println(err)
    39  
    40  	vm.Set("sayHello", func(call FunctionCall) Value {
    41  		fmt.Printf("Hello, %s.\n", call.Argument(0).String())
    42  		return UndefinedValue()
    43  	})
    44  
    45  	vm.Set("twoPlus", func(call FunctionCall) Value {
    46  		right, _ := call.Argument(0).ToInteger()
    47  		result, _ := vm.ToValue(2 + right)
    48  		return result
    49  	})
    50  
    51  	value, _ = vm.Run(`
    52          sayHello("Xyzzy");
    53          sayHello();
    54  
    55          result = twoPlus(2.0);
    56      `)
    57  	fmt.Println(value)
    58  
    59  	// Output:
    60  	// The value of abc is 4
    61  	// 4
    62  	// The value of def is 11
    63  	// 16
    64  	// 16
    65  	// undefined
    66  	// ReferenceError: 'abcdefghijlmnopqrstuvwxyz' is not defined
    67  	// Hello, Xyzzy.
    68  	// Hello, undefined.
    69  	// 4
    70  }
    71  
    72  func ExampleConsole() { //nolint: govet
    73  	vm := New()
    74  	console := map[string]interface{}{
    75  		"log": func(call FunctionCall) Value {
    76  			fmt.Println("console.log:", formatForConsole(call.ArgumentList))
    77  			return UndefinedValue()
    78  		},
    79  	}
    80  
    81  	err := vm.Set("console", console)
    82  	if err != nil {
    83  		panic(fmt.Errorf("console error: %w", err))
    84  	}
    85  
    86  	value, err := vm.Run(`console.log("Hello, World.");`)
    87  	fmt.Println(value)
    88  	fmt.Println(err)
    89  
    90  	// Output:
    91  	// console.log: Hello, World.
    92  	// undefined
    93  	// <nil>
    94  }