【问题标题】:Calling luabind derived member as a coroutine调用 luabind 派生成员作为协程
【发布时间】:2011-09-20 19:42:29
【问题描述】:

luabind 文档说要从 C++ 调用 Lua 派生的虚拟成员,您需要创建一个派生自 luabind::wrap_base 的包装类,然后像这样调用函数:

class BaseWrapper : public Base, public luabind::wrap_base
{
    public:
        virtual void foo()
        {
            call<void>("foo");
        }
};

到目前为止一切顺利 - 我有这么多工作。

但是我如何实现BaseWrapper::foo() 来调用被覆盖的foo(在Lua 端)作为协程(使用resume_function)而不是直接使用call 调用它?

这是对非成员函数的处理方式:

luabind::object func = luabind::globals(L)["bar"];
luabind::resume_function<void>(func);

我想我需要知道的是如何为foo 获取func(由Lua 派生类实现),然后我现有的resume_function 逻辑应该按原样工作。

【问题讨论】:

  • 明确地说,我不是在寻找 C++ 例程本身作为协程运行。我明白这是不可能的。在我的程序的实际架构中,它将 func 传递给我现有的协程调度程序并立即返回。
  • C++ 类 BaseWrapper 派生自 Lua 基类,但 C++ foo() 调用 Lua foo() 的部分让我迷失了方向。你能澄清一下吗?也许如果这两个 foo 不是真的相同,你可以重命名其中一个,或者添加 Lua 基类代码,或其他东西。
  • 它们应该命名相同,因为 Lua 在派生类中覆盖了 C++(在这种情况下,fooBase 的纯虚方法)。反正我已经想通了,一会儿再写答案。
  • 呃,我似乎还没有足够的声誉来发布我的答案。明天发。

标签: c++ lua luabind


【解决方案1】:

所以我已经找到了这个问题的答案。似乎最简单的解决方案是在构造对象时从 Lua 传递self,然后从其表中查找函数:

在 C++ 方面:

BaseWrapper::BaseWrapper(luabind::object self) : _self(self)
{ }

virtual void BaseWrapper::foo()
{
  luabind::object func = _self["foo"];

  /* now put func in coroutine scheduler queue and when appropriate call: 

     luabind::resume_function<void>(func, _self);
  */
}

在 Lua 中:

class 'Derived' (Base)
  function Derived:__init()
    Base.__init(self, self)     -- the second self is param to BaseWrapper()
  end

  function Derived:foo()
    -- here is the target function
  end
end

【讨论】:

  • 你应该能够遍历 lua 堆栈来确定那个自己吗? (也就是说,我不确定这些类是什么...... Lua 通常没有类)
猜你喜欢
  • 2012-04-21
  • 2011-09-16
  • 2018-04-06
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多