在 Lua 中注册 C++ 函数?

2021-12-30 00:00:00 lua c++

我正在尝试在 Lua 中注册一个 C++ 函数.

I am trying to register a c++ function in Lua.

但收到此错误:

CScript.cpp|39|error: argument of type 'int (CScript::)(lua_State*)' does not match 'int (*)(lua_State*)'|

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;
}

在主要部分:

lua_register(L, "setDisplayMode", Lua_SetDisplayMode);

推荐答案

您不能直接使用基本的 Lua C API 在 Lua 中注册 C++ 非静态成员函数.

You cannot directly register a C++ non-static member function in Lua using just the basic Lua C API.

然而,任何可以轻松将 C++ 代码与 Lua 相关联的各种机制都允许您这样做.toLua++、SWIG、Luabind 等.如果你是认真的在 Lua 中使用 C++ 对象,我建议选择其中之一并使用它,而不是编写自己的版本.我个人使用 Luabind(大部分时间;SWIG 在工具箱中占有一席之地),因为它没有某种形式的代码生成.这一切完全是在 C++ 中完成的,因此没有生成 C++ 源文件的预通过步骤.

However, any of the various mechanisms that exist for easily associating C++ code with Lua will allow you to do so. toLua++, SWIG, Luabind, etc. If you're serious about using C++ objects with Lua, I suggest picking one of those and using it, rather than writing your own version. I personally use Luabind (most of the time; SWIG has its place in the toolbox), as it is the one that doesn't have some form of code generation. It's all done purely in C++, so there's no pre-pass step that generates a C++ source file.

相关文章