2016-04-26 51 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)