Search code examples
luaffiluajit

How to merge clib functions into a table using LuaJIT and FFI?


I have a table/object defined in Lua. I'm trying to add some methods from a C-API dll. I could attach the methods one at a time, but there are a lot of them. The last line of the code below is how I would like to do it. It is supposed to merge the methods into the Utilities object so that I don't have to do them one at a time. I'm getting the following error:

bad argument #1 to 'pairs' (table expected, got userdata)"  const char *

Here is some sample code:

Utilities = {}

--
-- Other Code that defines/attaches methods to Utilities
-- 

-- Define some methods from my utilities.dll
local ffi = require("ffi")
ffi.cdef[[
void LogThis(const char * format, ...);
]]

local utilities_ffi = ffi.load("utilities")

-- This works
utilities_ffi.LogThis("hello world")

-- merge the two tables together (this fails)
for k,v in pairs(utilities_ffi) do Utilities[k] = v end

FFI must be returning a userdata object.


Solution

  • FFI library objects don't support iteration; you can't run pairs over them. You'll have to write an assignment for each function manually.

    Also keep in mind that it's faster to access C functions directly from the library object, rather than storing them in a table (or even a local variable) and accessing them there. See the last section of the FFI tutorial.