lua-users home
lua-l archive

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


Sorry I push the wrong button.

      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);
         return p;
     }

However,  there is a problem as to how the allocated block of memory
is divided between x_values and y_values. Are both x_values and
y_values given n * sizeof(double) , or x_values has 1*sizeof(double)
and y_values has (2*n-1)*sizeof(double)?  This ambiguity exists in any
userdata with more than one fields that need memory allocation
dynamically. Any one has thoughts on this issue?

Kuang
On Sun, Jan 17, 2010 at 2:29 PM, Kuang Chen <kchenphy@gmail.com> 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);
>