Implementing the C ++ -to-lua observer pattern?

I have a sample observer (or "listener") 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;
};

      

This now works in C ++; the Entity class calls the method entityModified()

whenever needed. Now I would like to pass some Lua functions, and among those function points is the listener callback. Entities are now created from Lua scripts. The question is, how do I achieve listener functionality in Lua?

For example, a Lua script is currently doing 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 listener
end

      

+3


source to share


1 answer


One possible solution is to have a class LuaListener

in your C ++ code that contains a "pointer" to a Lua function and a Lua-specific Lua function that is called from a Lua script that takes Lua as an argument and instantiates LuaListener

and passes it to actual C ++ setListener

.


Thus, the Lua code would look something like this:



function onModified(entity)
  -- ...
end

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

      

And the C ++ code would look something like (pseudo noise 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, ...));
    }
};

      

+3


source







All Articles