cocos2d-x与lua用法整理

来源:互联网 发布:linux下常用软件 编辑:程序博客网 时间:2024/04/27 17:02

Cocos2d-x 2.20以上版本没有了创建模板,创建的方式改用了Python创建,方法如下:

python create_project.py -project HelloWorld -package com.Panda.Game -language cpp

若要创建lua工程,结尾的cpp改成lua


然后创建出来的sln工程文件打开来,直接运行会发现已经是个成品了,有画面有音效有动画= =


工程的Resource文件夹下已经有一堆资源和脚本,AppDelegate的applicationDidFinishLaunching函数下已经写了脚本调用的代码了。想自己动手的可以从CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();开始删掉,并运行自己的scene:

pDirector->runWithScene(HelloLua::scene());


然后以下内容整理自木头的博客(http://blog.csdn.net/musicvs/article/details/8440707)和书籍(《cocos2d-x游戏开发之旅》)。感谢作者!

主要是理解C++和lua只能通过堆栈通信,理解lua堆栈的一些解析过程。

HelloLua.lua脚本如下:

myName = "PandaWu"
helloTable = {name = "Panda", IQ = 129}

function helloAdd(num1, num2, num3)
return (num1 + num2 + num3)
end


初始化,打开lua文件,设置堆栈指针:

lua_State* pL = lua_open();
luaopen_base(pL);
luaopen_math(pL);
luaopen_string(pL);

int err = luaL_dofile(pL, "HelloLua.lua");
CCLOG("open: %d", err);

lua_settop(pL, 0);


取myName变量:

lua_getglobal(pL, "myName");
int isstr = lua_isstring(pL, 1);
CCLOG("isstr = %d", isstr);
if (isstr != 0)
{
const char* str = lua_tostring(pL, 1);
CCLOG("get string %s", str);
}


取table中name和IQ:

lua_getglobal(pL, "helloTable");
lua_pushstring(pL, "name");
lua_gettable(pL, -2);
const char* name = lua_tostring(pL, -1);
CCLOG("%s", name);

lua_getglobal(pL, "helloTable");//这句还得写
lua_pushstring(pL, "IQ");//还是pushstring
lua_gettable(pL, -2);
int IQ = lua_tonumber(pL, -1);
CCLOG("%d", IQ);


调用lua中的helloAdd:

lua_getglobal(pL, "helloAdd");
lua_pushnumber(pL, 10);
lua_pushnumber(pL, 5);
lua_pushnumber(pL, 3);
lua_call(pL, 3, 1);//参数数量和返回值数量
int result = lua_tonumber(pL, -1);
CCLOG("result = %d", result);


最后:lua_close(pL);

0 0