Implementing C++ -to-lua observer pattern?

360 views Asked by At

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
1

There are 1 answers

0
Some programmer dude On BEST ANSWER

One possible solution is to have a LuaListener class in your C++ code that contains a "pointer" to the Lua function, and a Lua-specific setListener function that is called from the Lua script that takes a Lua function as argument, and creates a LuaListener instance and passes that to the actual C++ setListener.


So the Lua code would look something like

function onModified(entity)
  -- ...
end

function initializeEntity()
    entity = Helper.createEntity()
    entity.setListener(onModified)
end

And the C++ code would look something like (pseudoish-code only):

class LuaListener : public EntityListener
{
private:
    lua_State* state;
    std::string funcName;

public:
    void entityModified(Entity& e)
    {
        // Call function `funcName` in `state`, passing `e` as argument
    }
};

class LuaEntity : public Entity
{
public:
    void setListenerLua(state, funcName, ...)
    {
        Entity::setListener(new LuaListener(state, funcName, ...));
    }
};