otto是用原生Go编写的JavaScript解析器和解释器。
import ( "github.com/robertkrime/otto")在VM中运行
vm := otto.New()vm.Ru(` abc = 2 + 2; cosole.log("The value of abc is " + abc); // 4`)获取VM外的值
if value, err := vm.Get("abc"); err == il { if value_it, err := value.ToIteger(); err == il {fmt.Pritf("", value_it, err) }}设置数字
vm.Set("def", 11)vm.Ru(` cosole.log("The value of def is " + def); // The value of def is 11`)设置字符串
vm.Set("xyzzy", "Nothig happes.")vm.Ru(` cosole.log(xyzzy.legth); // 16`)获取表达式的值
value, _ = vm.Ru("xyzzy.legth"){ // value is a it64 with a value of 16 value, _ := value.ToIteger()}抛出错误
value, err = vm.Ru("abcdefghijlmopqrstuvwxyz.legth")if err != il { // err = RefereceError: abcdefghijlmopqrstuvwxyz is ot defied // If there is a error, the value.IsUdefied() is true ...}设置Go函数
vm.Set("sayHello", fuc(call otto.FuctioCall) otto.Value { fmt.Pritf("Hello, %s.\", call.Argumet(0).Strig()) retur otto.Value{}})在JS中使用函数
result, _ = vm.Ru(` sayHello("Xyzzy"); // Hello, Xyzzy. sayHello(); // Hello, udefied result = twoPlus(2.0); // 4`)
评论