cocos2d-x 3.x C++和Lua通信方式:Lua堆栈正数索引和负数索引的关系和用法

来源:互联网 发布:通讯网络与设备是什么 编辑:程序博客网 时间:2024/06/05 06:07

   用cocos2d-x  编写游戏的过程中,我们很可能会用到Lua文件。引用一本书上面的话,Lua最大的优势在于,不用重新编译项目就可以修改游戏逻辑,大大缩减了开发进程。我用的是cocos2d-x 3.x引擎,使用C++语言编写程序。C++和Lua之间的通信是通过Lua堆栈实现的。通信流程如图所示:



Lua堆栈索引如图:




索引分为正数索引和负数索引。正数索引的栈底索引值永远是1,负数索引的栈顶索引值永远是-1.

下面给出具体程序展示如何使用索引值:

第一步,新建一个helloLua.lua文件放在工程目录下面。helloLua.lua内容如下:

myName="hello Lua"
ID=2
helloTable={name="Lua",IQ=125}
function helloAdd(num1,num2)
return (num1+num2)
end


第二步:在cocos2d-x工程中新建一个类helloLua,.h文件和.cpp文件内容如下:

-----helloLua.h文件

#ifndef _HelloLua_H_
#define _HelloLua_H_

extern"C"{
#include<lua.h>
#include<lualib.h>
#include<lauxlib.h>
};
#include"cocos2d.h"
USING_NS_CC;
class HelloLua :public Layer
{
public:
CREATE_FUNC(HelloLua);
virtual bool init();
static Scene*createScene();
};
#endif


-----helloLua.cpp文件内容如下:

#include"HelloLua.h"
Scene* HelloLua::createScene()
{
auto scene = Scene::create();
auto layer = HelloLua::create();
scene->addChild(layer);
return scene;
}
bool HelloLua::init()
{
lua_State*pL = lua_open();
luaopen_base(pL);//
luaopen_math(pL);
luaopen_string(pL);
luaL_dofile(pL, "helloLua.lua");
lua_settop(pL, 0);


lua_getglobal(pL, "myName");
log("myName=%s", lua_tostring(pL, -1));

        lua_getglobal(pL, "ID");
log("ID=%s", lua_tostring(pL, -1));
log("myName=%s", lua_tostring(pL, -2));


lua_close(pL);
return true;
}


程序输出:myName=hello Lua
                 ID=2
                 myName=hello Lua


加入使用正数索引,上面红色的代码改成:

        lua_getglobal(pL, "myName");
log("myName=%s", lua_tostring(pL, 1));

        lua_getglobal(pL, "ID");
log("ID=%s", lua_tostring(pL, 2));
log("myName=%s", lua_tostring(pL, 1));

输出结果一样。

每次的结果都会保存在堆栈中。假如使用正数索引,第一个入栈的索引是1,接下来是2,3....。假如使用负数索引,最后一个入栈的索引是-1,之前一个是-2,-3....

正数索引和负数索引也可以混合使用,比如:上面的红色程序改为:

        lua_getglobal(pL, "myName");
log("myName=%s", lua_tostring(pL, 1));

        lua_getglobal(pL, "ID");
log("ID=%s", lua_tostring(pL, -1));
log("myName=%s", lua_tostring(pL, 1));

运行结果依然相同。




0 0
原创粉丝点击