实现C ++ -lua观察者模式? [英] Implementing C++ -to-lua observer pattern?

查看:155
本文介绍了实现C ++ -lua观察者模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中实现了一个观察者(或侦听器")模式,如下所示:

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;
};

现在,这可以在C ++中使用;实体类在需要时会调用entityModified()方法.现在,我想将某些功能转移到Lua,而在这些功能点中是此侦听器回调.现在,这些实体是通过Lua脚本创建的.问题是,如何在Lua中实现侦听器功能?

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?

例如,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

推荐答案

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

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.

因此Lua代码看起来像

So the Lua code would look something like

function onModified(entity)
  -- ...
end

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

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

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

这篇关于实现C ++ -lua观察者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆