【问题标题】:Implementing C++ -to-lua observer pattern?实现 C++ -to-lua 观察者模式?
【发布时间】:2015-01-30 16:28:22
【问题描述】:

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

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

【问题讨论】:

    标签: c++ lua luabridge


    【解决方案1】:

    一种可能的解决方案是在您的 C++ 代码中包含一个 LuaListener 类,该类包含一个指向 Lua 函数的“指针”,以及一个特定于 Lua 的 setListener 函数,该函数从采用 Lua 函数的 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, ...));
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2013-10-28
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      相关资源
      最近更新 更多