lua_pcall错误消息丢失

问题描述:

我使用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时可能会出现一些内存损坏,即某些事情会被搞砸了?

看来我需要拨打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); 

这就是现在的工作。