我正在尝试解决这个seg故障问题,当使用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 <iostream>
#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部分放在范围块中可以解决此问题。