从Lua调用C ++函数传递的参数较少

calling a c++ function from lua passes less arguments

本文关键字:参数 函数 Lua 调用      更新时间:2023-10-16

所以函数是这样的:

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)