【问题标题】:Handle event callbacks with Luabind使用 Luabind 处理事件回调
【发布时间】:2011-07-31 03:27:58
【问题描述】:

我正在将 Lua 脚本添加到我们的应用程序中,并且我需要为 GUI 工具包实现绑定。我们使用的工具包是 wxWidgets。

我使用的是 Lua 5.1 和 luabind 0.9.1,到目前为止运行良好。但是,我不确定如何最好地处理事件。例如,如果您想创建一个按钮并在单击时打印一个字符串,您可以在 C++ 中编写类似这样的内容

class MyClass : public wxFrame
{
    MyClass (...)
    {
        b = new wxButton (this, -1, "Click me");
        b->Bind (wxEVT_COMMAND_BUTTON_CLICKED, &MyClass::HandleButtonClick, this);
    }

    void HandleButtonClick (wxCommandEvent& ev)
    {
        wxMessageBox ("You clicked me");
    }
}

我在 Lua 中做同样事情的梦想 API 看起来像这样:

b = wx.Button (frm, -1, "Click me")
b.on_click = function (ev)
    print ("Button clicked")
end

或者,允许多个事件处理程序:

b.on_click:add (function (ev)
    print ("Button clicked again ...")
end)

如果不可能,像这样更类似于 C++ API 的东西:

b.bind (wx.EVT_COMMAND_BUTTON_CLICKED, function (ev)
    print ("Yet again")
end)

但是,如果不为 wxWidgets 库中我想要使用的每个类编写包装类,我不确定如何使用 Luabind 来实现这一点。

有什么建议吗?

也许 Luabind 可以以某种方式自动创建辅助类(比如“wxLuaEventPropagator”)?这样 wxButton 类对于每个事件(“on_click”等)都有一个嵌套的 wxLuaEventPropagator 类。再一次,我不想为我使用的 wxWidgets 中的每个类创建包装类,因为有很多。

(是的,我知道 wxLua)

【问题讨论】:

  • 你说你知道 wxLua - 那为什么不使用它呢?
  • 因为:1. wx-part 不会被脚本大量使用,而且我认为它是一个非常重的依赖项(尽管不一定如此),2. 项目可能会转移到另一个 gui 工具包不久的将来,最重要的是: 3. 还有其他的 api 我也必须包装,所以我仍然需要为此找到解决方案。我目前的计划是放弃 Luabind,尽管我非常喜欢它,而改用 SWIG。
  • 你提到了 C++。您的主机应用程序是用 C++ 编写的吗?
  • 我不熟悉 luabind。经过一番研究,我回答了自己的问题。
  • 错了乔纳森......我一直在思考这个问题,如果我想出一些新奇的东西可能会回答它。

标签: c++ lua luabind


【解决方案1】:

您可以使用 luabind::object 来做到这一点。

一个示例类: 我的班级 { 民众: 无效 OnMouseMoved(int x, int y); void SetEventFunction(const luabind::object &fn);

private:
    luabind::object m_eventFunction;
};


void MyClass::SetEventFunction(const luabind::object &fn)
{
    if(luabind::type(fn) == LUA_TFUNCTION)
    {
        cout << "A function" << endl;
        m_eventFunction = fn;
    }
    else
    {
        cout << "Not a function" << endl;
    }
}

void MyClass::OnMouseMoved(int x, int y)
{
    if(m_eventFunction.is_valid())
    {
        luabind::call_function<void>(m_eventFunction, x, y);
    }
}

在 lua 代码中,应该是:

myClass = MyClass()

myClass:SetEventFunction( function (x, y)
    print ("The new mouse position is", x, y)
end)

要对事件有多个功能,您可以使用std::vector of luabind::object

【讨论】:

  • 由于这些类是第 3 方库的一部分,因此我必须使用此方法包装每个类。正如我上面评论的那样,我现在使用的是 SWIG,因为它允许您以简单的方式扩展类。
猜你喜欢
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多