00001 /* 00002 http://www.opensource.org/licenses/mit-license.php (MIT-License) 00003 00004 Copyright (c) 2007 Lugre-Team 00005 00006 Permission is hereby granted, free of charge, to any person obtaining a copy 00007 of this software and associated documentation files (the "Software"), to deal 00008 in the Software without restriction, including without limitation the rights 00009 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 00010 copies of the Software, and to permit persons to whom the Software is 00011 furnished to do so, subject to the following conditions: 00012 00013 The above copyright notice and this permission notice shall be included in 00014 all copies or substantial portions of the Software. 00015 00016 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 00017 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 00018 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 00019 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 00020 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 00021 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 00022 THE SOFTWARE. 00023 */ 00024 #ifndef LUGRE_LUACALLBACK_H 00025 #define LUGRE_LUACALLBACK_H 00026 00027 #include "lugre_scripting.h" 00028 00029 extern "C" { 00030 #include "lua.h" 00031 #include "lauxlib.h" 00032 #include "lualib.h" 00033 } 00034 00035 namespace Lugre { 00036 00037 class LuaCallbackFunction { public: 00038 bool assigned; 00039 int fun; 00040 00041 // NOTE this contains the global lua state (scripting) not the 00042 // state from the assign parameters because coroutines 00043 // lua state could be non permanent. 00044 // 00045 // ie. (unverified) 00046 // coroutine L assignes the lua function 00047 // call 00048 // call 00049 // coroutine L ended 00050 // call -> booom 00051 lua_State *L; 00052 00053 void release() { 00054 if(assigned){ 00055 luaL_unref(L, LUA_REGISTRYINDEX, fun); 00056 assigned = false; 00057 } 00058 } 00059 00060 LuaCallbackFunction() : assigned(false), L(cScripting::GetSingletonPtr()->L) {} 00061 ~LuaCallbackFunction() { release(); } 00062 00063 00064 // assignes the lua function from then given stack index 00065 void assign(lua_State *L, int index) { 00066 release(); 00067 00068 // pushes the value 00069 lua_pushvalue(L, index); 00070 fun = luaL_ref(L, LUA_REGISTRYINDEX); 00071 00072 assigned = true; 00073 } 00074 00075 // calls the stored lua function 00076 // no args and no return values 00077 inline void SimpleCall(){ 00078 if(!assigned)return; 00079 00080 lua_rawgeti(L, LUA_REGISTRYINDEX, fun); 00081 //~ lua_call(L, 0, 0); 00082 if (PCallWithErrFuncWrapper(L,0,0) != 0) { 00083 LuaErrorHandler(L, "error running LuaCallbackFunction `%s': %s", "??", lua_tostring(L, -1)); 00084 } 00085 } 00086 }; 00087 }; 00088 00089 #endif
1.5.6