lua调用c++方法时,如何不绑定c++类只绑定函数(调用c++的全局函数,而不是类的成员函数)。我这里把全局函数写在了AppDelegate.h中。
----------1.添加全局函数
AppDelegate.h中在类外添加代码:
static int lua_cocos2dx_testFun(lua_State* L){ printf("这个是测试函数"); return 0;}
----------2.添加lua-bindingAppDelegate.cpp中的bool
AppDelegate::applicationDidFinishLaunching()方法中,在lua_module_register(L);前面加上
tolua_function(L,
"testFun", lua_cocos2dx_testFun);
----------3.lua中调用
testFun()
----------4.说明
tolua_function(L, "httpRequestFun",
lua_cocos2dx_HttpRequest_sendRequest);
这句话一定要加在lua_module_register(L);的前面。想弄明白为什么,需要了解lua-binding的具体细节,我还不是很清楚,有人说lua_module_register(L);中已经调用了模块,而直接绑定函数时,需要全局的lua_State*。
----------5.全部的bool
AppDelegate::applicationDidFinishLaunching()代码:
bool AppDelegate::applicationDidFinishLaunching()
{
// set default FPS
Director::getInstance()->setAnimationInterval(1.0 / 60.0f);
// register lua module
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
lua_State* L = engine->getLuaStack()->getLuaState();
tolua_function(L, "httpRequestFun", lua_cocos2dx_HttpRequest_sendRequest);
lua_module_register(L);
// tolua_function(L, "httpRequestFun", lua_cocos2dx_HttpRequest_sendRequest);
register_all_packages();
LuaStack* stack = engine->getLuaStack();
stack->setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA"));
//register custom function
//LuaStack* stack = engine->getLuaStack();
//register_custom_function(stack->getLuaState());
if (engine->executeScriptFile("src/main.lua"))
{
return false;
}
// glview->setDesignResolutionSize(1366, 768, ResolutionPolicy::FIXED_WIDTH);
return true;
}
原文:https://blog.youkuaiyun.com/u010536615/article/details/60869139