Implementing C++ -to-lua observer pattern?

匆匆过客 提交于 2019-12-10 19:54:43

问题


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:


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, ...));
    }
};


来源:https://stackoverflow.com/questions/27249195/implementing-c-to-lua-observer-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!