When is it allowed to call lua_gc in C ++ when lua_newuserdata is also used
Below is an example to demonstrate the problem / question; in fact I have functions creating and returning many different userdata objects and in between some of them I can call Lua a garbage collector.
Also, I am using Lua version 5.3.3 running on both Windows and Linux. Error handling is not shown for simplicity.
I have a C ++ class exposed by Lua via standard user data, as described for example in Programming in Lua by Roberto Ierasulsky. My problem is that I'm not sure when Lua has a reference to my object, so when am I allowed to call the garbage collector via the C ++ lua_gc function?
I have, for example, a standard C ++ class Foo with a constructor and destructor. And defined a meta-tagged "FOO" with an __gc input function called ReleaseFoo as shown also.
I am instantiating in Lua via the following C ++ code:
static int NewFoo(lua_State* L)
{
Foo** foo;
foo = (Foo**) lua_newuserdata(L, sizeof(Foo**));
*foo = new Foo();
luaL_getmetatable(L, "FOO");
lua_setmetatable(L, -2);
// QUESTION: Can I call lua_gc(L, LUA_GCCOLLECT, 0) here without
// risking my user data object being garbage collected.
// As I see it, Lua does not yet have a reference
// to my user data object.
return 1;
}
static int ReleaseFoo(lua_State* L)
{
Foo* foo = *(Foo**)lua_touserdata(L,1);
if (foo)
{
delete foo;
foo = NULL;
}
return 0;
}
In Lua, using it would look like (so it's only after the C ++ function NewFoo (L) returns that the link is set, but can I call the garbage collector as shown?):
LUA> foo = NewFoo()
source to share