lua-users home
lua-l archive

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


2010/10/19 Wesley Smith <wesley.hoke@gmail.com>:
>
> Really?  In the code you posted, all I saw was reference counting and
> zero use of weak tables.  Did you post the wrong code?

Sorry, Wesley, I was not clear enough. This was the code I was using
*before*. I've therefore switched to another model where I use weak
table instead of ref count. In the new model I have a weak table to
track what graphical elements are referenced by each plot. In this way
I don't need the ref count because it is Lua itself with its GC that
finalize the object when they are unreachable.

In the new code the plot finalizer is:

int
plot_free (lua_State *L)
{
  return object_free<Plot>(L, 1, GS_PLOT);
}

when I add a line to a plot I have something like that:

object_refs_add (L, table_plot_obj, p->current_layer_index(), 1, 2);

where object_refs_add is defined like this (it just add the object in
a weak table where the plot is the key):

void
object_refs_add (lua_State *L, int table, int index,
		 int key_index, int value_index)
{
  bool mult = table_mult_valued[table];

  INDEX_SET_ABS_2(L, key_index, value_index);

  lua_getfield (L, LUA_REGISTRYINDEX, table_name[table]);
  lua_pushvalue (L, key_index);
  lua_rawget (L, -2);

  if (lua_isnil (L, -1))
    {
      lua_pop (L, 1);
      lua_newtable (L);
      lua_pushvalue (L, key_index);
      lua_pushvalue (L, -2);
      lua_rawset (L, -4);
    }

  if (mult)
    mult_ref_add (L, index, -1, value_index);
  else
    {
      lua_pushvalue (L, value_index);
      lua_rawseti (L, -2, index);
    }

  lua_pop (L, 2);
}

The problem that I've got are:
- for table with weak keys the key object are not removed when they
are finalized but
  only at the following GC cycle => a Lua modification was needed
- during the lua_close all the userdatas are finalized in reverse
creation order. This can cause
  a segmentation fault because when the plot if deallocated it does
query its graphical
  elements to know if they are Lua allocated or not. It does need to
make this query because
  the Lua object are embedded in a arbitrary long chain of C++ objects
allocated on heap.
  Each of this object represent a graphical transformation like
stroking or making a dashed
  line or things like that. The C++ allocated objects need to be
deallocated with "delete" while
  the Lua allocated object should not because Lua manage its allocation.

-- 
Francesco