在Lua中注册c++函数

Register C++ function in Lua?

本文关键字:c++ 函数 注册 Lua      更新时间:2023-10-16

我正在尝试在Lua中注册c++函数。

但是得到这个错误:

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

main:

lua_register(L, "setDisplayMode", Lua_SetDisplayMode);

不能将类的方法作为普通函数使用,除非它被声明为static。您必须定义一个普通的函数,它找出您希望在哪个对象中调用该方法,然后调用该方法。

不可能使用类方法作为C函数的回调(记住Lua API是纯C库)的主要原因是计算机不知道应该在哪个对象上调用该方法。

答案其实非常简单;如果使用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);
    }

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

然而,任何一种可以轻松地将c++代码与Lua关联起来的机制都允许您这样做。tolua++, SWIG, Luabind等。如果您认真考虑在Lua中使用c++对象,我建议您选择其中一个并使用它,而不是编写自己的版本。我个人使用Luabind(大部分时间;SWIG在工具箱中有它的位置),因为它没有某种形式的代码生成。这一切都是完全用c++完成的,所以没有预传递步骤来生成c++源文件。

您也可以通过将活动this指针存储在静态变量中来解决这个限制。这就引入了一个问题,即不能让两个类同时运行,但它是有效的。

static CScript* luaThis; // This is a private variable inside CScript.
然后,在CScript构造函数(或某种"激活"函数)中,您可以指定:
luaThis = this;

然后,当你的静态函数被调用时(如果它们是从类中注册的,它们甚至可以是私有函数),你可以通过luaThis指针访问所有的成员信息。

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

问题,正如我所说的,这限制了你一次一个活动的CScript(因为另一个Lua状态的回调会使用luaThis,而它指向错误的东西)。如果您需要多个活动实例,您可以使用传入的lua_State*作为键来提出一些查找机制。

std::map<lua_State*, CScript*> lookups; // Just an idea, if it comes to this.

希望有帮助!