lua-users home
lua-l archive

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


Lyte _ wrote:
I have some problems with adding a metatable to userdata for garbage collection. This is what I have now... When i start lua I do the following.

luaL_newmetatable(L, "LuaBook.gc_event");

/* set its __gc field */
lua_pushstring(L, "__gc");
lua_pushcfunction(L, gc_function);
lua_settable(L, -3);

I then call a factory function from lua which creates an object in C. I want to be able to free this object the right way when it is not used anymore, but it does not seem to work. This is what I do in the factory function.

lua_newuserdata(L,sizeof(...))
luaL_getmetatable(L, "LuaBook.gc_event");
lua_setmetatable(L, -2);'

In the Lua program, I then do something like this.

o = CreateObject()
o = nil
collectgarbage()

When I run this the function I added to the metatable does not get called. What am I doing wrong here?

You probably forgot to assign the "__index" field
of the metatable to the metatable itself:

  luaL_newmetatable(L, "LuaBook.gc_event");
  lua_pushliteral(L, "__index");
  lua_pushvalue(L, -2);         /* push metatable */
  lua_rawset(L, -3);            /* metatable.__index = metatable */

--
Shmuel