Game Development Reference
In-Depth Information
Event System
Communication between C++ and Lua is inevitable, and there needs to be a system
to facilitate that communication. A naive approach might be to expose all the meth-
ods you need to Lua and allow them to be called directly. This would probably work
just fine, but it would end up being very messy. You
'
ll have dozens or even hundreds
of methods exposed to Lua, and this tightly couples your engine to the Lua script. If
one of those methods changes, you
'
ll have to update all the appropriate places in the
script as well.
A much better approach is to use the event system we already created in Chapter 11,
Game Event Management, and extend it in a similar way that we extended the pro-
cess system. Unfortunately, this won
s one thing to create a self-
contained process with very little data that needs to cross the C++ / Lua boundary,
and it
'
t be as easy. It
'
s quite another to facilitate that communication.
The first thing you need is a special type of event that can be sent to or from Lua. This
event should take care of all the data translation as well. The goal is for the receiver of
the event to have no idea where it came from. You should be able to send an event
that ' s received by both Lua and C++ without either knowing of the source. This
keeps it all nice and decoupled, which is the whole point of the event system.
Here
'
s the ScriptEvent class, which serves as the base class for all events that need
to cross the C++ / Lua boundary:
'
#define REGISTER_SCRIPT_EVENT(eventClass, eventType) \
ScriptEvent::RegisterEventTypeWithScript(#eventClass, eventType); \
ScriptEvent::AddCreationFunction(eventType, \
&eventClass::CreateEventForScript)
#define EXPORT_FOR_SCRIPT_EVENT(eventClass) \
public: \
static ScriptEvent* CreateEventForScript(void) \
{\
return new eventClass; \
}
// function ptr typedef to create a script event
typedef ScriptEvent* (*CreateEventForScriptFunctionType)(void);
class ScriptEvent : public BaseEventData
{
typedef std::map<EventType, CreateEventForScriptFunctionType>
CreationFunctions;
static CreationFunctions s_creationFunctions;
bool m_eventDataIsValid;
 
 
Search WWH ::




Custom Search