2016-03-16 138 views
1

我使用lua_pcall來調用某個函數,我想要捕獲錯誤。 在某些情況下,錯誤似乎會丟失。這怎麼可能發生? 這適用於我使用錯誤處理程序和不使用時的情況。在這兩種情況下,堆棧的頂部都不是字符串。lua_pcall錯誤消息丟失

C代碼:

lua_getglobal(L, "debug"); 
    lua_getfield(L, -1, "traceback"); 
    lua_replace(L, -2); 
    lua_rawgeti(L, LUA_REGISTRYINDEX, my_func_index); 
    // now push n_in number of values on the stack 
    luaT_stackdump(L); 
    int pcall_ret = lua_pcall(L, n_in, n_out, -n_in - 2); 
    // lua_pcall will consume n_in+1 values from the stack. 
    if(pcall_ret != 0) { 
    const char* errmsg = lua_tostring(L, -1); 
    if(!errmsg) { 
     errmsg = "(No Lua error message.)"; 
     printf("Unexpected Lua stack:\n"); 
     luaT_stackdump(L); 
    } 
    printf("Lua error code %i: %s\n", pcall_ret, errmsg); 
    lua_pop(L, 2); // remove error and debug.traceback from the stack 
    return ...; 
    } 
    // now we got n_out values on the stack 

這就是所謂的Lua的功能看起來像這樣(用於測試):

function (x, W, b, index) 
     print "hi from Lua func" 
     A = torch.rand(15, 12) 
     B = torch.rand(12, 23) 
     C = torch.dot(A, B) 
    end 

當它調用torch.dot這多少會得到一個錯誤。 但我不完全知道爲什麼。我沒有得到任何有意義的錯誤。 這就是我的問題所在。

輸出:

1. Lua object type: function 
    2. Lua object type: function 
    3. userdata 4165a368 [torch.FloatTensor] 
    4. userdata 4165a390 [torch.FloatTensor] 
    5. userdata 4165a230 [torch.FloatTensor] 
    6. userdata 4165a258 [torch.CharTensor] 
--------------------------------------------- 
hi from Lua func 
Unexpected Lua stack: 
    1. Lua object type: function 
    2. userdata 40ea1230 [torch.DoubleTensor] 
--------------------------------------------- 
Lua error code 2: (No Lua error message.) 

或者,也許我的代碼是正確的,它真的應該在這裏返回錯誤字符串?所以在撥打torch.dot時可能會出現一些內存損壞,即某些事情會被搞砸了?

回答

0

看來我需要撥打torch.updateerrorhandlers()。然後,我得到一些有意義的輸出:

hi from Lua func 
Lua error code 2: inconsistent tensor size at /tmp/luarocks_torch-scm-1-1092/torch7/lib/TH/generic/THTensorMath.c:384 
stack traceback: 
     [C]: at 0x7f63cd831360 
     [C]: in function 'dot' 
     [string "return ..."]:9: in function <[string "return ..."]:2> 

但是,只有當我有torch.updateerrorhandlers()的Lua的函數內。

我試着用這種C代碼和不工作:

lua_getglobal(L, "torch"); 
    lua_getfield(L, -1, "updateerrorhandlers"); 
    lua_replace(L, -2); 
    assert(lua_pcall(L, 0, 0, 0) == 0); 

我想通了,如果我的權利我的實際my_func_indexlua_pcall,它的工作原理之前,做的是另torch.updateerrorhandlers()電話。 這是意想不到的,但也許這是因爲這可能是另一個線程 (我不會期望)。 其實,我在火炬代碼中發現的功能torch.updatethreadlocals()這正是爲了這個目的,現在我打電話這一個,我的其他lua_pcall前右:

lua_getglobal(L, "torch"); 
    lua_getfield(L, -1, "updatethreadlocals"); 
    lua_replace(L, -2); 
    assert(lua_pcall(L, 0, 0, 0) == 0); 

這就是現在的工作。