lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Memory for userdata is allocated and freed by Lua. There's nothing special about userdata in tables, at least from the perspective of the Lua C API. Lua has no knowledge of C++ constructors and destructors, but it does support __gc metamethods in the metatables of userdata. So to wrap an instance of a class called Foo in Lua userdata, you'd write code like this:

Foo **pp = (Foo *) lua_newuserdata(L, sizeof(Foo *));
*pp = new Foo;

Then you'd set the new userdata's metatable to a table with a __gc metamethod like this:

static int foo_gc(lua_State *L) {
  Foo **pp = (Foo **) lua_touserdata(L, 1);
  if (*pp) {
    delete *pp;
    *pp = NULL;
  }
  return 0;
}

Actually, to be foolproof, any C functions which take userdata as arguments, including __gc metamethods, should check for the correct metatable. But that's beside the point here.

Your C++ code need not be concerned about how many references to the userdata are passed around within Lua. Just implement a __gc metamethod as shown above, and Lua will take care of the rest.

Matt