在Lua中注册C++函数?

Cob*_*bra 1 c++ lua

我想在Lua中注册一个c ++函数.

但是得到这个错误:

CScript.cpp|39|error: argument of type 'int (CScript::)(lua_State*)' does not match 'int (*)(lua_State*)'|
Run Code Online (Sandbox Code Playgroud)

编辑:

int CApp::SetDisplayMode(int Width, int Height, int Depth)
{
    this->Screen_Width = Width;
    this->Screen_Height = Height;
    this->Screen_Depth = Depth;

    return 0;
}

int CScript::Lua_SetDisplayMode(lua_State* L)
{
  // We need at least one parameter
  int n = lua_gettop(L);
  if(n < 0)
  {
    lua_pushstring(L, "Not enough parameter.");
    lua_error(L);
  }

  int width = lua_tointeger(L, 1);
  int height = lua_tointeger(L, 2);
  int depth = lua_tointeger(L, 3);

  lua_pushinteger(L, App->SetDisplayMode(width, height, depth));

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在主要:

lua_register(L, "setDisplayMode", Lua_SetDisplayMode);
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 7

除非声明了类,否则不能将类的方法用作普通函数static.您必须定义一个普通函数,它找出您希望调用该方法的对象,然后调用该方法.

无法使用类方法作为来自C函数的回调(并且记住Lua API是纯C库)的主要原因是因为计算机不知道应该调用该方法的对象.


Phi*_*llo 5

答案其实出奇的简单;如果您使用 lua_pushcclosure 而不是 lua_pushcfunction,则可以将参数传递给被调用的函数:

    lua_pushlightuserdata(_state, this);
    lua_pushcclosure(_state, &MyClass::lua_static_helper, 1);

    int MyClass::lua_static_helper(lua_State *state) {
        MyClass *klass = (MyClass *) lua_touserdata(state, lua_upvalueindex(1));
        return klass->lua_member_method(state);
    }
Run Code Online (Sandbox Code Playgroud)