lua-users home
lua-l archive

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


On Sun, May 29, 2011 at 6:11 PM, Justin Cormack
<justin@specialbusservice.com> wrote:
> You can tell if something is a cdata struct or array by using pcall (a >
> nil) as a test, as only pointer types can be compared with nil (ie NULL),
> and arrays and structs will give an exception. There might be another way,
> but this works. Then if it is a struct or array you can do ffi.sizeof.
> ie print(ffi.new("int[3]") > nil) throws an exception
> but print(ffi.cast("void *", ffi.new("int[3]")) > nil) is true.

Thank you for the suggestion - but unfortunately it looks like the
nil-comparison trick only works with void*, and not other kinds of
pointer:

 test = ffi.new 'struct { int* intptr; }'
 print(test.intptr > nil)   -->  attempt to compare 'void *' with 'int *'

But it did give me another idea - checking that the value could be
cast to a void*, but that it is *not* possible to cast nil/NULL to the
value's type:

 -- "full" cdata, as in Lua's concept of "full" vs. "light" userdata
 function isfullcdata(v)
   return (type(v) == 'cdata')
      and pcall(ffi.cast, 'void*', v)
      and not pcall(ffi.cast, ffi.typeof(v), nil)
 end

This seems to fix the pointer-type issue, can you see any other
problems with it?

-Duncan