Nil and NULL

  • From: QuentinC <webmaster@xxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 05 Aug 2012 18:12:13 +0200


Would it be possible to do so that cdata pointers pointing to NULL gets translated in lua either to actual nil, or at least be interpreted as being false in a if/while statement ?

The usecase is very simple: an FFI function creates an object and returns a pointer to the created object, but sometimes the creation can fail for whatever reason.

Basic example with malloc :
ffi.cdef[[ void* malloc (int size); ]]
local pointer = ffi.C.malloc(123)
if not pointer then print('malloc failed') end -- this looks reasonably correct but is actually not

The if is never executed. IF the malloc fails, it returns a cdata encapsuling a NULL pointer, and this cdata is interpreted as true anyway. I think that a NULL cdata pointer should be converted to false when using in a if statement as I did above (of course not only void* but all pointers)

Notice also that there isn't any simple way to check the nullity: currently the way I found is to convert first to intptr_t, then to number with the tonumber function, and finally compare it to 0 :

function isnull (pointer)
local intval = ffi.cast('intptr_t', pointer)
local num = tonumber(intval)
return num==0

Quite long just for a so trivial operation, isn't it ?

Other related posts: