MyAppTheme Logo2

Blog

Alles rund um's iPhone

Lightweight integration of Lua in Objective-C

Lightweight integration of Lua in Objective-C

Based on the great article about integrating Lua in your own iApp written by Robert Grzesek, I’ve written a lightweight wrapper in Objectice-C and will explain how it can be used to scripting games written with Cocos2D and LevelSVG. The attached example project itself contains none of those library for copyright reason’s, so uses UIView only to show the approach. But anybody should be easy possible to extend it for his own game.

My personal version of RBLuaInterpreter class is supporting all node’s of LevelSVG  and can be directly attached to objects in xml. So no programming is needed at all. Now to the concepts behind, but before that please read Robert’s Blog where to downloaf Lua itself and how its integrated in your project. The C++ class written by him end’s with the standard mechanism how to call Lua and back to C, so that’s exactly the same here in my class. The “trick” is to add some scripting extensions where I can pass LevelSVG BodyNode objects to Lua and call then method’s out of Lua which change behavior in the calling object or other GameNode child objects.

In the example attached, it’s done with the help of a tag id, so it’s also easy to request an object from GameNode object and call them back.

Below is a sample Lua script, which give’s you an idea how it looks like in my game. Of course, Lua allow’s also a more OO approach, but for us it was not important to use the language in it’s best but to have a full scriptable engine. But some of the nice Lua feature’s like returning multiple parameters from a function are implemented of course.

So feel free to download the attached project, use the class and let me know what you’ve done based on that. Happy (game) coding!

Example Screenshot of LuaTest

--
-- Game object scripts are called with events
--
-- init: When level is created and before it starts
-- exit: When game object is released
-- contactbegin: When contact with other game object begins
-- contactend: When contact with other game object ends
-- bullettouches: When game object is touched by bullet
-- herotouches: When game object is touched by hero
--
-- show balks (id 1,2) and hide balk (id 3,4)
--
print("BEGIN level1-13-showbalks.lua");
objectId = arg[1];
event = arg[2];
--
if (event == "bullettouches") then
balk1 = level.getObject(1);
object.setHidden(balk1, 0);
balk2 = level.getObject(2);
object.setHidden(balk2, 0);
balk3 = level.getObject(3);
object.setHidden(balk3, 1);
balk4 = level.getObject(4);
object.setHidden(balk4, 1);
end
--
print("END level1-13-showbalks.lua");