尝试调用在表中定义的lua函数时出现段错误。

我正在尝试解决这个 seg fault 问题,它在 luabind 中从 C++ 调用在表中定义的 lua 函数时出现。这是 C++ 代码(引用自 In C++, using luabind, call function defined in lua file?http://lua.2524044.n2.nabble.com/How-to-call-a-Lua-function-which-has-been-defined-in-a-table-td7583235.html ):

```extern "C" { #include <lua5.2/lua.h> #include <lua5.2/lualib.h> #include <lua5.2/lauxlib.h> }

#include #include <luabind/luabind.hpp> #include <luabind/function.hpp>

int main() { lua_State *myLuaState = luaL_newstate(); luaL_openlibs(myLuaState); luaL_dofile(myLuaState, "test.lua"); luabind::open(myLuaState);

luabind::object func = luabind::globals(myLuaState)["t"]["f"]; // Line #1
int value = luabind::call_function<int>(func, 2, 3); // Line #2
std::cout << value << "\n";
lua_close(myLuaState);

}```

这是 lua 代码:

t = { f = function (a, b) return a+b end } -- Line #3

该程序编译为:

g++ test.cpp -I/usr/include/lua5.2 -llua5.2 -lluabind

cpp 程序的输出是:

5 Segmentation fault (core dumped)

带有回溯的输出:

```#0 0x00007ffff7bb0a10 in lua_rawgeti () from /usr/lib/x86_64-linux-gnu/liblua5.2.so.0

#1 0x00007ffff7bc27f1 in luaL_unref () from /usr/lib/x86_64-linux-gnu/liblua5.2.so.0

#2 0x0000000000401bb5 in luabind::handle::~handle() ()

#3 0x0000000000401e15 in luabind::adl::object::~object() ()

#4 0x000000000040185c in main ()```

然而,如果 lua 函数被定义为全局函数,我就不会看到任何错误,即将第 3 行更改为:

f = function (a, b) return a+b end

并将第 2 行更改为

int value = luabind::call_function<int>(myLuaState, "f", 2, 3);

所以我的问题是:

  • 为什么会这样?
  • 这是调用表中函数的正确方法吗?

按照@EtanReisner 的评论,正确的解决方法是:

将 call_function 部分放入作用域块中将解决此问题。

点赞