lua_pcall错误消息丢失

时间:2016-03-16 14:48:16

标签: lua torch

我使用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时可能会有一些内存损坏,即某些东西搞砸了?

1 个答案:

答案 0 :(得分: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>

但是只有我在Lua函数中有torch.updateerrorhandlers()

我尝试使用此C代码,但这不起作用:

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

我发现,如果我在实际的torch.updateerrorhandlers() my_func_index之前进行了另一次lua_pcall来电,那就可以了。 这是意料之外的,但也许这是因为这可能是另一个线程 (我不希望这样)。 实际上,我在Torch代码中找到了函数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);

现在可以使用了。

相关问题