Reputation: 1286
I am trying to solve this seg fault problem, arised when a lua function defined in a table is called from C++ using luabind. Here is C++ the code (borrowed from In C++, using luabind, call function defined in lua file?, and 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);
}
and here is the lua code:
t = { f = function (a, b) return a+b end } -- Line #3
The program is compiled with
g++ test.cpp -I/usr/include/lua5.2 -llua5.2 -lluabind
The output of the cpp program is
5
Segmentation fault (core dumped)
with the backtrace:
#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 ()
However, I don't see any error if the lua function is instead defined as a global, i.e change line #3 to read
f = function (a, b) return a+b end
and line #2 is changed to
int value = luabind::call_function<int>(myLuaState, "f", 2, 3);
So my question is:
Why is this happening?
Is this the correct way to call functions in a table?
Per @EtanReisner comment, the correct solution is:
Putting the call_function part in a scope block would solve this problem.
Upvotes: 1
Views: 842