您的位置:首页 > 移动开发 > Cocos引擎

在Cocos2d-x工程中嵌套使用Lua

2015-07-23 16:49 477 查看
一、配置环境

首先到Lua官网(http://www.lua.org)下载Lua的源代码,解压后得到有如下内容的文件夹:



在终端中打开src文件夹,并输入以下命令编译出mac os x 平台下的lau/laux/liblua.a:

make macosx


首先我们需要将src目录复制到Xcode工程目录下,然后将liblua.a添加到工程的引用库中,如下图所示:



并在工程属性的Build Settings中找到Header Search Paths中添加该lua文件夹的路径,以保证可以再文件中include这些文件:



二、在CPP文件中使用

我就直接贴代码了,注意中间的引用文件部分:

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

extern "C"
{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}

class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();

// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();

// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);

// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__


一个最简单的lua堆栈实例:

bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}

//创建一个state
lua_State* L = luaL_newstate();

//开始入栈
lua_pushstring(L, "I'm so cool");
lua_pushnumber(L, 2);

//取值操作
if (lua_isstring(L, 1)) {
log("%s", lua_tostring(L, 1));
}
if (lua_isnumber(L, 2)) {
log("%f", lua_tonumber(L, 2));
}

//关闭
lua_close(L);

return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: