cocos2d-x 2.2.0 如何在lua中注册回调函数给C++
cocos2d-x内部使用tolua进行lua绑定,但是引擎并没有提供一个通用的接口让我们可以把一个lua函数注册给C++层面的回调事件。 下面以一个简单的消息分发类为例子,演示如何完成这一工作。 MessageDispatcher.hclass MessageDispather { public: static MessageDispather* sharedDispather(); public: void invokeLuaCallbackFunction(int msgId,const char* text); void registerScriptHandler(int nHandler); private: int mLuaHandlerId; };
MessageDispatcher.cpp#include "CCLuaEngine.h" MessageDispather* sharedDispather() { static MessageDispather* instance = NULL; if(instance == NULL) instance = new MessageDispather(); return instance; } void MessageDispather::invokeLuaCallbackFunction(int msgId,const char* text) { if(mScriptHandler > 0) { CCLuaStack* stack = CCLuaEngine::defaultEngine()->getLuaStack(); stack->pushInt(msgId); stack->pushString(text); stack->executeFunctionByHandler(mScriptHandler,2); stack->clean(); } } void MessageDispather::registerScriptHandler(int nHandler) { mLuaHandlerId = nHandler; }
说明 用于tolua的pkg文件class MessageDispather { static MessageDispather* sharedDispather(); void registerScriptHandler(LUA_FUNCTION nHandler); };
在lua中使用MessageDispatcherlocal function onMessage(msgId,text) print(msgId,text) end MessageDispatcher:sharedDispatcher():registerScriptHandler(onMessage)
万事大吉。。。。。才怪! 有没有发现我们的pkg文件中有一个类型是 那么我们可以照猫画虎,请创建这样一个lua文件: _is_functions = _is_functions or {} _to_functions = _to_functions or {} -- register LUA_FUNCTION,LUA_TABLE,LUA_HANDLE type _to_functions["LUA_FUNCTION"] = "toluafix_ref_function" _is_functions["LUA_FUNCTION"] = "toluafix_isfunction" _to_functions["LUA_TABLE"] = "toluafix_totable" _is_functions["LUA_TABLE"] = "toluafix_istable" local toWrite = {} local currentString = '' local out local WRITE,OUTPUT = write,output function output(s) out = _OUTPUT output = OUTPUT -- restore output(s) end function write(a) if out == _OUTPUT then currentString = currentString .. a if string.sub(currentString,-1) == 'n' then toWrite[#toWrite+1] = currentString currentString = '' end else WRITE(a) end end function post_output_hook(package) local result = table.concat(toWrite) local function replace(pattern,replacement) local k = 0 local nxt,currentString = 1,'' repeat local s,e = string.find(result,pattern,nxt,true) if e then currentString = currentString .. string.sub(result,s-1) .. replacement nxt = e + 1 k = k + 1 end until not e result = currentString..string.sub(result,nxt) if k == 0 then print('Pattern not replaced',pattern) end end replace([[*((LUA_FUNCTION*)]],[[(]]) replace([[tolua_usertype(tolua_S,"LUA_FUNCTION");]],[[]]) WRITE(result) end
然后在你执行tolua++的时候把这个文件作为-L参数传进去就可以了。 到这里,应该就可以正常生成了。 当时我遇到了运行时出现错误的情况。 修改成这样就没有问题了 LUA_FUNCTION luaCallback = toluafix_ref_function(tolua_S,2,0); 主要是自动生成的回调函数等号右边会出现强制类型转换,但是这样就会报错 把这个去掉就可以了。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |