// DoString ... func (state *LuaState) DoString(script string) (string, error) { code := C.CString(script) defer C.free(unsafe.Pointer(code)) C.luaL_loadstring(state.lua, code) C.lua_pcallk(state.lua, 0, LuaMultRet, 0, 0, nil) return "", nil }
// Calls a function in protected mode. // // Both nargs and nresults have the same meaning as in Call. If there are // no errors during the call, Pcall behaves exactly like Call. However, // if there is any error, Pcall catches it, pushes a single value on the // stack (the error message), and returns an error code. Like Call, Pcall // always removes the function and its arguments from the stack. // // If errfunc is 0, then the error message returned on the stack is exactly // the original error message. Otherwise, errfunc is the stack index of // an error handler function. (In the current implementation, this index // cannot be a pseudo-index.) In case of runtime errors, this function // will be called with the error message and its return value will be the // message returned on the stack by Pcall. // // Typically, the error handler function is used to add more debug // information to the error message, such as a stack traceback. Such // information cannot be gathered after the return of Pcall, since by then // the stack has unwound. func (this *State) Pcall(nargs, nresults, errfunc int) error { defer func() { if r := recover(); r != nil { fmt.Println(r.(string)) } }() r := int(C.lua_pcallk(this.luastate, C.int(nargs), C.int(nresults), C.int(errfunc), C.int(0), nil)) return this.geterror(r) }
func (self *Lua) CallFunction(name string, args ...interface{}) { defer func() { if r := recover(); r != nil { if self.PrintTraceback { //NOCOVER print("============ start lua traceback ============\n") self.RunString(`print(debug.traceback())`) print("============ end lua traceback ==============\n") } panic(r) } }() cName := cstr(name) C.setup_message_handler(self.State) C.lua_getglobal(self.State, cName) for _, arg := range args { self.PushGoValue(reflect.ValueOf(arg)) } ret := C.lua_pcallk(self.State, C.int(len(args)), 0, C.lua_gettop(self.State)-C.int(len(args)+2), 0, nil) if ret != C.int(0) { self.Panic("%s", C.GoString(C.lua_tolstring(self.State, -1, nil))) } }
func (self *Lua) RunString(code string) { defer func() { if r := recover(); r != nil { if self.PrintTraceback { //NOCOVER print("============ start lua traceback ============\n") self.RunString(`print(debug.traceback())`) print("============ end lua traceback ==============\n") } panic(r) } }() cCode := cstr(code) C.setup_message_handler(self.State) if ret := C.luaL_loadstring(self.State, cCode); ret != C.int(0) { self.Panic("%s", C.GoString(C.lua_tolstring(self.State, -1, nil))) } ret := C.lua_pcallk(self.State, 0, 0, C.lua_gettop(self.State)-C.int(1), 0, nil) if ret != C.int(0) { self.Panic("%s", C.GoString(C.lua_tolstring(self.State, -1, nil))) } C.lua_settop(self.State, 0) }