从Lua调用C ++函数传递的参数较少
calling a c++ function from lua passes less arguments
所以函数是这样的:
send_success(lua_State *L){
MailService *mls = static_cast<MailService *>(lua_touserdata(L, lua_upvalueindex(1)));
Device *dev = static_cast<Device *>(lua_touserdata(L, lua_upvalueindex(2)));
int numArgs = lua_gettop(L);
TRACE << "Number of arguments passed is = " << numArgs;
/* here I do some operation to get the arguments.
I am expecting total of 5 arguments on the stack.
3 arguments are passed from function call in lua
and 2 arguments are pushed as closure
*/
string one_param = lua_tostring(L, 3, NULL)
string two_param = lua_tostring(L, 4, NULL)
string other_param = lua_tostring(L, 5, NULL)
}
现在在lua堆栈上推送这个函数,我已经完成了以下操作
lua_pushstring(theLua, "sendSuccess");
lua_pushlightuserdata(theLua, (void*) mls);
lua_pushlightuserdata(theLua, (void*) this);
lua_pushcclosure(theLua, lua_send_success,2);
lua_rawset(theLua, lua_device); // this gets me device obj in lua
从Lua调用它,我会做的
obj:sendSuccess("one param","second param","third param")
但是当我检查参数的数量时。它应该给出 5 个参数。相反,只传递 4 个参数。我做了一些测试,测试了我传递灯光使用数据的两个对象是否正确传递。它们已正确传递。
这里唯一缺少的是,缺少一个从lua端传递的参数。
我也尝试只推送一个对象,它工作正常。 所以我不确定我是否在某处搞砸了参数编号
请说出您的意见
作为闭包的一部分创建的用户数据对象不会作为参数传递给函数,而是放置在状态的另一个位置。
这意味着您用来获取带有lua_tostring
参数的偏移量是错误的。
好的。
lua_pushclosure
将用户数据保存在lua_stack
上的单独空间中。在该堆栈中,偏移量 1 和 2 表示第一个和第二个对象
lua_pushlightuserdata(theLua, (void*) mls);
lua_pushlightuserdata(theLua, (void*) this);
lua_pushcclosure(theLua, lua_send_success,2);
但在那之后,我要去第三个 3rd,假设我已经访问了第二个位置。但这是错误的。正确的做法是考虑pushclousure
只占用堆栈上的一个空间,无论lightuserdata
被推送多少次,并且可以通过从第二个偏移量开始访问剩余的参数。所以下面的代码对我有用:
string one_param = lua_tostring(L, 2, NULL)
string two_param = lua_tostring(L, 3, NULL)
string other_param = lua_tostring(L, 4, NULL)
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类