I have an observer (or "listener") pattern implemented in my code as such:
struct EntityListener
{
public:
virtual void entityModified(Entity& e) = 0;
};
class Entity
{
public:
Entity();
void setListener(EntityListener* listener);
private:
EntityListener* m_listener;
};
Now, this works in C++; the Entity class calls the entityModified()
method whenever it needs. Now, I'd like to transfer some of the functionality to Lua, and among those function points is this listener callback. The entities are now created from the Lua scripts. The question is, how do I achieve the listener functionality in Lua?
For example, the Lua script currently does something like this:
function initializeEntity()
-- The entity object is actually created in C++ by the helper
Entity = Helper.createEntity()
-- Here I'd like to hook a Lua function as the Entity's listener
end
One possible solution is to have a
LuaListener
class in your C++ code that contains a "pointer" to the Lua function, and a Lua-specificsetListener
function that is called from the Lua script that takes a Lua function as argument, and creates aLuaListener
instance and passes that to the actual C++setListener
.So the Lua code would look something like
And the C++ code would look something like (pseudoish-code only):