lua-users home
lua-l archive

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


Thanks for your help! I had forgotten to do lua_pop(L, 1), although I don't know if that was the problem. The problem was that the object in Lua was not nil, so it did not get garbage collected. But everything works fine now! Thanks again!
Regards

- Lyte


From: Vyacheslav Egorov <mraleph@gorodok.net>
Reply-To: Lua list <lua@bazar2.conectiva.com.br>
To: Lua list <lua@bazar2.conectiva.com.br>
Subject: Re: Garbage collection
Date: Sun, 10 Sep 2006 18:18:03 +0700

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

Looks fine. But could you please inform us what Lua version you are using. How you check whether __gc metamethod gets called or not. Can is it possible that CreateObject leves reference to return value somewhere. Could it be that you modified metatable of global environment? Try inserting some assertions just after luaL_getmetatable (for example ASSERT(lua_istable(L, -1))), etc. Also try to provide complete minimal example representing your problem. Because the following example works fine with Lua 5.1.1:

// begin code
#include "lua.h"
#include "lauxlib.h"
#include <stdio.h>

static int gc_function (lua_State *L) {
 printf("GC!\n");
 return 0;
}

static void registermt(lua_State *L) {
 luaL_newmetatable(L, "LuaBook.gc_event");

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

 lua_pop(L, 1); /* pop mt */
}

static int create(lua_State *L) {
 lua_newuserdata(L, sizeof(char));
 luaL_getmetatable(L, "LuaBook.gc_event");
 lua_setmetatable(L, -2);
 return 1;
}

int main() {
 lua_State *L = luaL_newstate();
 registermt(L);
 lua_register(L, "create", create);  luaL_openlibs(L);
 luaL_dostring(L, "o = create();"                  \
                  "o = nil;"                       \
                  "print 'before collectgarbage';" \
                  "collectgarbage();"                \
                  "print 'after collectgarbage';");  lua_close(L);
 return 0;
}
// end code

--
e.v.e


_________________________________________________________________
Dags att flytta till större? http://sokbostad.msn.se