lua-users home
lua-l archive

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


Here's another issue I encountered with __gc: it appears that userdata
created inside a finalizer does not have its finalizer called.  This
leaks any resources associated with the userdata.  This test prints
"Created" but not "GC'd" in both 5.1 and 5.2.

--

#include "lauxlib.h"
#include <stdio.h>

#if LUA_VERSION_NUM == 501
#define setfuncs(L, l) luaL_register(L, NULL, l)
#elif LUA_VERSION_NUM == 502
#define setfuncs(L, l) luaL_setfuncs(L, l, 0)
#endif

static int gc(lua_State *L) {
  printf("GC'd\n");
  return 0;
}

static const struct luaL_Reg mm[] = {
  {"__gc", gc},
  {NULL, NULL}
};

int luaopen_ext(lua_State *L) {
  printf("Created\n");
  lua_newuserdata(L, 0);
  lua_newtable(L);
  setfuncs(L, mm);
  lua_setmetatable(L, -2);
  return 1;
}

--

if _VERSION >= 'Lua 5.2' then
  function defer(fn)
    setmetatable({}, { __gc = fn })
  end
else
  function defer(fn)
    getmetatable(newproxy(true)).__gc = fn
  end
end

defer(function() require "ext" end)