예제 #1
0
func ExampleRegister_sandbox() {
	const code = `
    Print("foo")
    Print(io ~= nil)
    Print(os == nil)
`

	L := luar.Init()
	defer L.Close()

	res := L.LoadString(code)
	if res != 0 {
		msg := L.ToString(-1)
		fmt.Println("could not compile", msg)
	}

	// Create a empty sandbox.
	L.NewTable()
	// "*" means "use table on top of the stack."
	luar.Register(L, "*", luar.Map{
		"Print": fmt.Println,
	})
	env := luar.NewLuaObject(L, -1)
	G := luar.Global(L)

	// We can copy any Lua object from "G" to env with 'Set', e.g.:
	//   env.Set("print", G.Get("print"))
	// A more convenient and efficient way is to do a bulk copy with 'Setv':
	env.Setv(G, "print", "io")

	// Set up sandbox.
	L.SetfEnv(-2)

	// Run 'code' chunk.
	err := L.Call(0, 0)
	if err != nil {
		fmt.Println("could not run", err)
	}
	// Output:
	// foo
	// true
	// true
}
예제 #2
0
파일: sandbox.go 프로젝트: EncoreJiang/luar
func main() {
	L := luar.Init()
	defer L.Close()

	gettop := func() {
		fmt.Println("top", L.GetTop())
	}
	gettop()

	// compile chunk
	res := L.LoadString(test)
	if res != 0 {
		msg := L.ToString(-1)
		fmt.Println("could not compile", msg)
	}

	// create environment for chunk
	L.NewTable()
	// "*" means use table on stack....
	luar.Register(L, "*", luar.Map{
		"Print": fmt.Println,
	})
	env := luar.NewLuaObject(L, -1)
	G := luar.Global(L)
	//~ env.Set("print",G.Get("print"))
	//~ env.Set("io",G.Get("io"))
	// more convenient/efficient way to do a bulk copy
	env.Setv(G, "print", "io")
	L.SetfEnv(-2)

	// run chunk
	err := L.Call(0, 0)
	if err != nil {
		fmt.Println("could not run", err)
	}

}