function to check if a symbol in a library exists or not

  • From: Cosmin Apreutesei <cosmin.apreutesei@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Mon, 30 Jul 2012 09:46:36 +0300


Sometimes I need to know at runtime if a symbol is defined in a
library or not. Take cairo for instance, which contains the
appropriate symbols only for the backends that it was compiled with,
and it doesn't give you a "capabilities" API to tell you which those
backends are.

So I keep reinventing this small utility which I wish it would be part
of ffi already:

 local function access(lib,symbol) return lib[symbol] end
 function ffi.check(lib,symbol)
   local ok,v = pcall(access,lib,symbol)
   if ok then return v else return nil end

Then use it like this:

ffi.metatype('cairo_surface_t', {__index = {
        finish = check(cairo, 'cairo_surface_finish'),
        destroy = check(cairo, 'cairo_surface_destroy'),
        xlib_set_size = check(cairo, 'cairo_xlib_surface_set_size'),
        xlib_set_drawable = check(cairo, 'cairo_xlib_surface_set_drawable'),

cairo_xlib_surface_set_size is a symbol which may or may not be there,
but I can only populate the metatype table once so I can't give the
user an option to "enable" the use of xlib after the module is loaded.

Btw, I think it would be more in the spirit of Lua if the ffi wouldn't
break at all when a symbol is not found and just return nil instead. I
wouldn't even need the check function then, and it would make life
easier, like with the metatype table constructor above.

Other related posts: