Wednesday, March 2, 2011

iPhone - Cocos2D + Lua - Part 2

This is a continuation of my Part 1 tutorial.

This is the part 2 of my Lua/Cocos2D integration. Sorry for the delays but I've been busy, then sick, and now still sick and trying to get some work done. Updates are limited and I hope this helps out someone. At this point I've cleaned up the LuaBridge and added a LuaMenu layer. I have an idea for a game I will build using this project and these are good parts to start.

LuaBridge has been reduced to simple declarations:

static const CCNode *ccnode;
static const CCNode *ccmenu;
int lua(const char *, const char *, const luaL_Reg *);

ccnode and ccmenu are my shared variable with which the bridge interacts with active Cocos layer. lua is the main function which takes in the script name, the class name which will define my c function in Lua and a structure to my c functions.

LuaBridge also created a file path for the Lua script being called. When adding additional Lua scripts it's important to add them to the target project. Do this by right clicking on the Lua script, click Get Info, click Targets and check off your project, in my case LuaCocos2D.

When the Cocos2D menu layer is initialized the first thing it does is call the LuaMenu with the script. LuaMenu is a wrapper around Cocos2D menu functions that can be executed with Lua calls. This means that Lua can now begin interactive with the game without recompiling each time.

This by no means wraps the entire menu layer because it's not the useful part. Menu's do not change that often and do not depend on too many parameters. However, it is the easiest way to illustrate the connection and it is much easier to make changes in Lua instead of Code.

Inside the LuaMenu is a structure:

static const luaL_Reg menu_funcs[] = {
{"new", new_menu},
{"add", add_menu},
{"render", render_menu},

This is what gets passed to Lua script and Lua can call the C functions. When the function returns Lua expects it to be of type static int with luaState as the only argument. The arguments are returned on the stack and can be returned via:
const char *title = luaL_checkstring(l, 2);

The 1st argument on the stack is the pointer to the stack table and not needed for this purposes.

With returned values from Lua it's a simple matter of calling the appropriate Cocos2D functions and adding them to they layer.

Till next time! :) Let me know if notice any errors, have correction or better ideas for implementation. I am constantly re factoring the code and looking for better ways to do things.

Git your code here: :)