2016-04-26 76 views
1

因此函数是这样的:调用从Lua C++函数传递少参数

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个参数。 我做了一些测试,我是否传递了一个光使用的数据是正确传递的两个对象。它们正确传递。

只有在这里缺少的东西是,一个参数丢失,从卢阿方传递。

另外我试着只推动一个对象,它工作正常。所以我不知道如果我用争论编号某处

请告诉您的意见

回答

0

用户数据对象创建的闭包函数的自变量都没有通过的部分搞乱了,他们把在该州的另一个地点。

这意味着用于获取参数lua_tostring的偏移量是错误的。

+0

你能举个例子说明我应该如何得到实际的参数,以我的例子作为上下文吗? –

0

好的。所以事情是

lua_pushclosure保持用户数据在lua_stack单独的空间。这堆里面,偏移​​1和2分别为第1和第2个对象

lua_pushlightuserdata(theLua, (void*) mls); 
lua_pushlightuserdata(theLua, (void*) this); 
lua_pushcclosure(theLua, lua_send_success,2); 

但在那之后我要到第三第三,假设我已经进入第二位置。但这是错误的。做正确的事情是考虑pushclousure发生在堆栈只有一个空格,不论多少次lightuserdata推及其余PARAMS可以通过从第二偏移..所以下面的代码开始访问对我的作品:

string one_param = lua_tostring(L, 2, NULL) 
    string two_param = lua_tostring(L, 3, NULL) 
    string other_param = lua_tostring(L, 4, NULL)