集成Lua

 键入如下命令,安装 XCode 的模板。
1
sudo ./install-templates.sh

这样 cocos2d 的模板就安装好了。

将下载好的 Lua 文件包解压到一个文件夹,准备好。

然后打开 XCode,创建新项目:

创建 cocos2d 项目

我们选择 cocos2d 模板,创建名为“TestLua”的项目。

可以试着运行一下,iOS 模拟器会启动,并且显示一行“Hello World”在画面中间。

这时查看输出信息,可以看到最后几行如下的跟踪信息:

1
2
3
4
2012-02-01 21:45:10.452 TestLua[2136:10a03] cocos2d: compiled with VBOsupport in TextureAtlas : YES
2012-02-01 21:45:10.453 TestLua[2136:10a03] cocos2d: compiled with AffineMatrix transformation in CCNode : YES
2012-02-01 21:45:10.453 TestLua[2136:10a03] cocos2d: compiled with ProfilingSupport: NO
2012-02-01 21:45:10.527 TestLua[2136:10a03] cocos2d: surface size: 480x320

在 XCode 界面的最左侧选择项目列表的第一行(写着“TestLua”那行),然后在界面中间下方找到“Add Target”,点击它。

在弹出的 Target 对话框中进行如下选择创建静态库的 Target:

创建新的 Target:静态库

给新的 Target 命名为“Lua”,然后再回到左侧项目文件列表上,右键选择“Add Files to “TestLua””:

引入文件

在弹出的选择框中选择解压好的 Lua 文件夹。记得将其加入到 Lua 目标中去。

选择 lua 5.2.0

准备工作就做好了,可以再次运行测试一下,如果一切正常,那么还会看见刚才的画面。


下面开始写测试代码。

在左侧找到 HelloWorldLayer.m 文件,将其改名为 HelloWorldLayer.mm,标识为 C++ 文件。

点击 HelloWorldLayer.mm,XCode 界面右侧就会出现源代码。找到这行:

1
#import "HelloWorldLayer.h"

在这行代码下面写入如下代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//
//
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};
 
int runlua(void) {
 
lua_State *L = luaL_newstate();
 
// load the libs
luaL_openlibs(L);
printf("nLua done!n");
lua_close(L);
 
return 0;
}

这样,我们就加入了一段最简单的 Lua 代码到程序中。不过这还不算完,我们要调用它试验一下。

还是在 HelloWorldLayer.mm 中,找到 scene 方法,添加针对 runlua 方法的调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
+(CCScene *) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];
 
    // 'layer' is an autorelease object.
    HelloWorldLayer *layer = [HelloWorldLayer node];
 
    // add layer as a child to scene
    [scene addChild: layer];
 
    // 执行 lua 方法
    runlua();
 
    // return the scene
    return scene;
}

现在,试着再运行一下。

画面没有什么变化,但是看一下输出:

1
2
3
4
5
6
2012-02-01 21:45:10.452 TestLua[2136:10a03] cocos2d: compiled with VBOsupport in TextureAtlas : YES
2012-02-01 21:45:10.453 TestLua[2136:10a03] cocos2d: compiled with AffineMatrix transformation in CCNode : YES
2012-02-01 21:45:10.453 TestLua[2136:10a03] cocos2d: compiled with ProfilingSupport: NO
2012-02-01 21:45:10.527 TestLua[2136:10a03] cocos2d: surface size: 480x320
 
Lua done!

 

看到最后一行了吗?说明我们的 Lua 代码被正确执行了!这样,我们就成功实现了在 cocos2d 里面对 Lua 程序的调用。

好,现在,该去好好学习 Lua 啦。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值