Search code examples
luaffiluajit

Can i load multiple libraries with ffi.load in LuaJIT?


Is it possible to load more than one library at same time with LuaJIT's ffi.load?

Can something like this works?

local ffi = require("ffi")
local bor = require("bit").bor
ffi.cdef([[
   // C bindings from each library!
]])
return ffi.load(bor("lib1", "lib2", "lib3"))

Solution

  • You can't really import multiples libraries to a single userdata due to the way LuaJIT FFI library works. The only thing you can easily do is to call userdata getter in a protected call as LuaJIT FFI throw an error on undefined symbol, and loop each library you want to fetch.

    local function get(t, k)
      return t[k]
    end
    
    local superlib = setmetatable({
      ffi.load "a",
      ffi.load "b",
      ffi.load "c"
    }, {
      __index = function (self, k, v)
        for _,l in ipairs(self) do
          local status, val = pcall(get, l, k)
          if status then
            return val
          end
        end
      end
    })