lua-users home
lua-l archive

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

On Sun, May 29, 2011 at 4:42 PM, Duncan Cross <> wrote:
On Sun, May 29, 2011 at 4:26 PM, Justin Cormack
<> wrote:
>> A. Determining 'one of a set of special cdata types' (2). I have tried
>> using tostring(ffi.typeof(value)) and looking this up in a table, and
>> it seems to work, but should I trust this method to be future-proof?
> No thats not the recommended method, you should use ffi.istype(type, val)
> which returns true if it is that type.

Oh, I forgot about that, oops.

It does mean I need to go through a (possibly large) array of types
and check each one rather than looking up a single identifying token
once though, which doesn't seem ideal, but JIT can probably help with
that for all I know.

I believe it does.
> You could in addition support duck typing, ie also
> accept anything that has a ptr and len method as well.

That's true. cdatas will throw an error if you try to index them to
look to see if a method exists, though, but I could put it in a pcall.

Yes, pcall helps here. I think it has to, otherwise there would be no sane way to distinguish between a real null pointer and not set/existing.
>> Also, it strikes me that stage (2) would not be necessary if it were
>> possible to apply (4) to these cdata values instead of special-casing
>> them. I know there are heavy restrictions on the metatables of cdata,
>> and that is understandable. But I'm wondering if it would be possible
>> to call custom metamethods on cdata with something like a
>> ffi.metacall(cdata, '__mymetamethod')?
> Why cant you just add a __tobuffer metamethod to all the types?

getmetatable(cdata) always seems to return 'ffi', currently.

You have to use ffi.metatype() to set a metatable. eg

fd_t = ffi.metatype("struct {int fd;}", {__index = {close = close}, __gc = close})

This can only be done on creation, but works nicely.