在Lua中注册c++函数
Register C++ function in Lua?
我正在尝试在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.
希望有帮助!
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗