lua-users home
lua-l archive

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

On Sun, Jan 17, 2010 at 5:29 PM, Kuang Chen <> wrote:
> Hi,
>       I would like to define an array with the following structure:
>      typedef struct
>      {
>          int size;
>          double x_values[1];  /* x variable part */
>          double y_values[1];  /* y variable part */
>      } PairArray;
>      As you can see, it is quite similar to the NumArray defined in
> ch28, pil, with the only difference being that there are a pair of
> values (x,y) for each index. The size of PairArray is provided by user
> at run time. Therefore, I wrote a "new" function for PairArray , which
> is again similar to the one on pil:
>      static PairArray PairArray_alloc(lua_State *L, int size)
>      {
>          size_t nbytes = sizeof(PairArray) + 2*sizeof(double)*(size-1);
>          PairArray* p  = (PairArray*)lua_newuserdata(L, nbytes);

You didn't get to the question, but I think I can guess it.  This code
is wrong because without special handling, your two arrays will
overlap.  I find it much easier to use pointers.

struct pairarray { double *x, double *y; };

p = lua_newuserdata(L, sizeof(*p) + sizeof(double) * 2 * size);
p->x = (double *)(p + 1);
p->y = p->x + size;

Technically, you use a little more memory for the pointers.  Really, I
don't think it matters and it's more understandable.