键入如下命令,安装 XCode 的模板。
|
|
sudo ./install-templates.sh
|
这样 cocos2d 的模板就安装好了。
将下载好的 Lua 文件包解压到一个文件夹,准备好。
然后打开 XCode,创建新项目:

我们选择 cocos2d 模板,创建名为“TestLua”的项目。
可以试着运行一下,iOS 模拟器会启动,并且显示一行“Hello World”在画面中间。
这时查看输出信息,可以看到最后几行如下的跟踪信息:
|
|
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 命名为“Lua”,然后再回到左侧项目文件列表上,右键选择“Add Files to “TestLua””:

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

准备工作就做好了,可以再次运行测试一下,如果一切正常,那么还会看见刚才的画面。
下面开始写测试代码。
在左侧找到 HelloWorldLayer.m 文件,将其改名为 HelloWorldLayer.mm,标识为 C++ 文件。
点击 HelloWorldLayer.mm,XCode 界面右侧就会出现源代码。找到这行:
|
|
#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;
}
|
现在,试着再运行一下。
画面没有什么变化,但是看一下输出:
|
|
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 啦。