使用Luabind处理事件回调。

我正在将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)

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

有什么建议吗?

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

(是的,我知道wxLua)

原文链接 https://stackoverflow.com/questions/5572249

点赞
stackoverflow用户595105
stackoverflow用户595105

你可以使用luabind::object来实现这个。

一个例子类:

class MyClass
{
public:
    void 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::vectorluabind::object

2011-05-26 07:20:19