如何在 Lua 中注册函数时使用 std::bind?

在问题“如何在 C++ 中不使用 Lua 绑定注册成员函数到 Lua” 一个答案建议使用以下代码:

class C {
   public:
      void blah(lua_State* L);
};

C inst;

lua_pushcclosure(L, std::bind(&C::blah, &inst, std::placeholder::_1), 0);
lua_setglobal(L, "blah");

(引用原文,包括使用 std::placeholders 时的小错误)

然而,我无法让它起作用。我收到的错误消息指出,std::bind 返回的函数无法转换为 lua_CFunction

我还尝试将 blah 的返回类型更改为 int,但我得到相同的错误消息。如果对任何人有帮助,完整的错误消息是:

Error   C2664   'void lua_pushcclosure(lua_State *,lua_CFunction,int)': cannot convert argument 2 from 'std::_Binder<std::_Unforced,int (__thiscall C::* )(lua_State *),C *,const std::_Ph<1> &>' to 'lua_CFunction'

我甚至尝试将 &C::blah 更改为 &inst.blah,但那当然也行不通。

有人让它工作了吗?还是它根本不适合工作?

点赞