May 30, 2014
Scripting the Engine with Lua
The next thing to add to the engine is scripting support using the popular Lua scripting language. This will facilitate the implementation of triggers, event handling, and even more complex things like storylines and scripted cutscenes. I have implemented partial Lua support, but there are a few details that require attention before Lua can be fully supported.
The Goal
The goal is to be able to access entities, their components, and specific properties from Lua scripts for the purpose of getting, setting, and tweening. By adding script support, developers and designers will be able to attach arbitrary actions to specific entities. In a level’s definition (either in text format or in a level editor), scripts will be attached to specific entity events like onCollisionStart, onCollisionEnd, and onDamageReceived. These events will be fired from various systems. Here’s what a button’s onCollisionStart event might look like in Lua:
game.tween(
-- The component to tween
entities.gate.LGTransform,
-- The property to tween
"positionY",
-- The target value
entities.gate.LGTransform.positionY - entities.gate.LGCollider.height,
-- Optional settings, i.e. open in 0.5 seconds
{ seconds = 0.5 }
)
In this example, when something collides with the button (or the button trigger area), the button’s onCollisionStart event will be fired. The script will be called, and the entity tagged as “gate” will have its transform’s positionY property adjusted by its collider’s height property. The gate will be open, and the player will be able to go through.
Considerations
Before this kind of script will be possible, the functionality for it must exist within the engine. There are a three features the engine currently lacks that will be required. Once these implemented, adding Lua support is as simple as mapping the script to these engine functions.
- A way to look up an entity by a tag (such as “gate”). This feature will most likely be implemented by adding an
NSMutableDictionaryto theLGSceneclass that maps tags to entities. - A way to access properties as primitives, such as
doublevalues (rather than only asCGPointstructs). We can add component properties (i.e. x, y, width, height) that have getters and setters using the appropriateCGPointorCGSizefield. - A way to tween properties. A tweening system can be added to the scene for this purpose.
I have quick and dirty implementations of these features already completed, and Lua scripts running in the engine successfully. When I’ve polished it up, I will push my code to the repository and give more details on how it works.