lua-users home
lua-l archive

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


2010/10/18 Wesley Smith <wesley.hoke@gmail.com>:
> So, what happens in this case in C++?
>
>
> Plot *p = new Plot();
> Line *l = new Line();
> p->add_line(l);
> delete p;
>
> Is Line l invalid?  When it's added to the Plot does Plot take
> ownership?  Increment a reference count?  Seems like you have the same
> problems in C++ as you would with Lua.

Hi Wesley,

I'll explain you how I was doing before and how I'm doing (with a lot
of pain) now.

Before:

#include <new>

inline void* operator new(size_t nbytes, lua_State *L, enum gs_type_e tp)
{
  void* p = lua_newuserdata(L, nbytes);
  gs_set_metatable (L, tp); /* custom function to set metatable */
  return p;
}

template <class T>
T* push_new_object (lua_State *L, enum gs_type_e tp)
{
  try
    {
      return new(L, tp) T();
    }
  catch (std::bad_alloc&)
    {
      luaL_error (L, "out of memory");
    }

  return 0;
}

template <class T>
int object_unref (lua_State *L, int index, enum gs_type_e tp)
{
  T *obj = (T *) gs_check_userdata (L, index, tp);
  obj->unref();
  return 0;
}

template <class T>
T* object_check (lua_State *L, int index, enum gs_type_e tp)
{
  return (T *) gs_check_userdata (L, index, tp);
}

/* Plot and Line are C++ classes with reference counting */

Plot::~Plot()
{
  for each line ln()
  {
    ln->unref();
  }
}

Plot *p = push_new_object<Plot>(L, GS_PLOT);
Line *ln = push_new_object<Line>(L, GS_LINE);

/* plot finalizer */
int plot_free (Lua_state *L)
{
  /* unref an object at stack position 1 */
  return object_unref<Plot>(L, 1, GS_PLOT);
}

/* line finalizer */
int line_free (Lua_state *L)
{
  /* unref an object at stack position 1 */
  return object_unref<Line>(L, 1, GS_LINE);
}

int plot_add_line (Lua_State *L)
{
  Plot *p  = object_check<Plot>(L, 2, GS_PLOT);
  Line *ln = object_check<Line>(L, 2, GS_LINE);

  /* We add the line to the plot. This function will also increment
     the reference count of ln. */
  p->add_line(ln);
}

What I'm doing now is to avoid to use reference counting. I'm using
instead Lua native mechanisms and I've a lot of troubles. Probably I
will switch back to the old method.

More specifically I'm using weak tables to track which object does
make reference to which object (for example which plot make reference
to which line).

-- 
Francesco