实现C ++ -to-lua观察者模式?

时间:2014-12-02 12:12:57

标签: c++ lua luabridge

我在我的代码中实现了一个观察者(或“监听器”)模式:

struct EntityListener
{
public:
    virtual void entityModified(Entity& e) = 0;
};

class Entity
{
public:
    Entity();
    void setListener(EntityListener* listener);
private:
    EntityListener* m_listener;
};

现在,这适用于C ++; Entity类在需要时调用entityModified()方法。现在,我想将一些功能转移到Lua,这些功能点之间就是这个监听器回调。现在,这些实体是从Lua脚本创建的。问题是,如何在Lua中实现监听器功能?

例如,Lua脚本目前执行以下操作:

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 个答案:

答案 0 :(得分:3)

一种可能的解决方案是在C ++代码中包含一个LuaListener类,其中包含一个指向Lua函数的“指针”,以及一个从Lua脚本调用的特定于Lua的setListener函数。将Lua函数作为参数,并创建一个LuaListener实例并将其传递给实际的C ++ setListener


所以Lua代码看起来像

function onModified(entity)
  -- ...
end

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

C ++代码看起来像(仅限伪代码):

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, ...));
    }
};
相关问题