lua-users home
lua-l archive

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


Thank you very much. I'm now reading both Sean Conner's recommendations and yours. I notice some remarks by Sean resemble code already present in lmapm, so I'll read your libraries more carefully. Thanks again.

Cordially,

Jairo

El mié, 20 de oct. de 2021 a la(s) 06:51, Luiz Henrique de Figueiredo (lhf@tecgraf.puc-rio.br) escribió:
I haven't tested your code but here are some remarks from reading it.

> //Is this right?
>   gsl_vector *r = (gsl_vector *)lua_newuserdata(L, sizeof(gsl_vector));
>   *r = *t;

Yes.

>   luaL_getmetatable(L, VECTOR_MT);
>   lua_setmetatable(L, -2);

This is right but in Lua 5.2+ you can use
    luaL_setmetatable(L, VECTOR_MT);
I suggest you create a function Pnew(L) that creates a udata at and
use it throughout.

>   gsl_vector *v = (gsl_vector *)lua_touserdata(L,1);

This is dangerous. You need to ensure that the udata has the proper type:
    gsl_vector *v =  (gsl_vector *)luaL_checkudata(L,1,VECTOR_MT);
Otherwise your binding will crash when maliciously called with bad
data trying to be a vector.

I suggest you create a function Pget(L,i) that gets a udata at
position i and use it throughout.

> 2. According to some docs I've read, userdata content should be freed by defining a function for __gc. However, I don't understand when or how to do that, as defining a function using gsl_vector_free in the case above is giving me an error prompt complaining about an invalid pointer.

Create a __gc method in the metatable that removes the metatable from
a udata and calls gsl_vector_free.

See my libraries at https://web.tecgraf.puc-rio.br/~lhf/ftp/lua/ ,
especially say lbc and lmapm which adopt different strategies for
creating udata depending on whether the underlying library allows
stack objects or insists on allocating them. In the first case, the
binding uses lua_newuserdata; in the second case it uses boxed
pointers (which is what you have done).