cocos升级到2.1.4之后,越来越能看到开发团队对LUA的重视,恨不得除了个别组件用cpp处理,其他的内容都用LUA来写。
LUA的好处是很多的,比如更新方便,开发快捷,学习成本低等等。
手头有一个项目,启动时采用cpp作为核心解决方案,但最近客户反映需要引入LUA脚本,并且要求LUA脚本的动态更新。查了一些资料,现将解决方案汇总如下:
1,关于LUA
我开发的环境是VC2010+cocos2d-x2.1.4
因为创建工程时没有勾选[LUA脚本支持],所以这里要手动配置,在 项目属性的 [VC++ 目录]里的[包含目录]里,添加[你的cocos项目路径\scripting\lua]路径。
在[链接器->输入]里添加[liblua.lib lua51.lib]两个lib文件。
在需要读取LUA脚本的cpp里,添加 #include "cocos2dx_support/CCLuaEngine.h"。
这样,就可以使用LUA脚本了。
查看了cocos2d-x自带的HelloLUA工程和TestsLUA工程,发现它们都是以LUA为主体的,而我的项目是以CPP为主体,以LUA为辅助的。
我的需求是:在cpp中调用LUA脚本,生成一个界面(这个界面要频繁的在线更新),在cpp工程中,我可以得到这个界面的指针。
查看了CCLuaEngine.h之后,并没有发现合适的接口来实现这一功能。
于是,我决定在函数virtual int executeGlobalFunction(const char* functionName);的基础上,自己写一个函数,来满足我的要求。
virtual bool executeGlobalFunctionX(const char* functionName, const char* _Format, ... );
{
//获得State
lua_State* pMyState = m_stack->getLuaState();
lua_getglobal(pMyState, functionName); /* query function by name, stack: function */
if (!lua_isfunction(pMyState, -1))
{
CCLOG("[LUA ERROR] name '%s' does not represent a Lua function", functionName);
lua_pop(pMyState, 1);
return false;
}
int inArgsNum = 0, outArgsNum = 0;
va_list args;
va_start(args, _Format);
char* buff = new char(strlen(_Format) + 1);
strcpy(buff, _Format);
char *ptr = NULL;
ptr = strtok( buff, "%" );
//get in args
do
{
if (strcmp(ptr, "d") == 0 ) //int
{
lua_pushnumber(pMyState, va_arg(args, int));
inArgsNum++;
ptr = strtok( NULL, "%" );
continue;
}
else if (strcmp(ptr, "f") == 0 ) //int
{