lua-users home
lua-l archive

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


On Thu, Sep 2, 2010 at 9:40 PM, Ted Unangst <ted.unangst@gmail.com> wrote:
> On Thu, Sep 2, 2010 at 4:33 PM, Peter Cawley <lua@corsix.org> wrote:
>> On Thu, Sep 2, 2010 at 9:27 PM, Ted Unangst <ted.unangst@gmail.com> wrote:
>>> And allocating the real data as userdata too, and then hanging a reference
>>> to it, gets to be a pain.
>>
>> I don't see why it should be any more painful than normal memory
>> management in C, using something like the following:
>
> Unless I have vastly misunderstood your proposal, these user data
> would never be garbage collected.  Explicit frees in Lua are no more
> painful than explicit frees in C, but I'd prefer to let the garbage
> collector do its job.
>
>>
>> void* malloc_lua(size_t sz, lua_State* L)
>> {
>>  void* p = lua_newuserdata(L, sz);
>>  lua_pushlightuserdata(L, p);
>>  lua_insert(L, -2);
>>  lua_settable(L, LUA_REGISTRYINDEX);
>>  return p;
>> }
>>
>> void free_lua(void* p, lua_State* L)
>> {
>>  lua_pushlightuserdata(L, p);
>>  lua_pushnil(L);
>>  lua_settable(L, LUA_REGISTRYINDEX);
>> }

My proposal is that the current image-related code is taken, and then
the calls to malloc/free which deal with the large buffer are replaced
with calls to some generic allocator. Then the above Lua-based
allocator is used as the generic allocator, meaning that the garbage
collector is aware that there is this large block of memory floating
around. This causes the Lua GC to run collections at better intervals,
which should cause the proper image userdata to be collected. In turn,
the __gc method on the proper userdata will eventually call the
generic free function on its large buffer, which calls the lua
allocator free function, which causes the large buffer to be garbage
collected in the next cycle.