lua-users home
lua-l archive

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

BTW, here are a couple of pointers for working with FFI.

C->Lua calls

You can't call into LUA using FFI, but you can call using the existing
pcall mechanism.  If you want to pass C data structures to lua
functions, you can do that too.  Simply push a lightuserdata
containing the address of the C structure, and on the lua side
ffi.cast() it to a pointer to the c type.


struct WorkData data;
lua_pushlightuserdata(L, &data);

function processData(dataPtr)
  local data = ffi.cast("WorkData*", dataPtr)

  -- use it

Make sure to cast it to (WorkData*), not just WorkData, or else you'll
get an error (which makes sense, since you pushed the address as a

Lua -> old-style lua C functions

If you need to call into a C function you've exposed to lua using
openLib or register, and want to pass a C data structure, just call
the function normally on the lua side.  On the C side, you need to
check to see if the lua_type() is 10 (which represents CDATA - hmmm...
it would be nice to have lua_iscdata).  Then, you can call
lua_topointer on it, which will give you a pointer to the structure.

int luaCopyBuffer(lua_State* L)
   if (lua_type(L, 1) == 10) // CDATA
      struct Buffer* pBuffer = (Buffer*)lua_topointer(L,1);
      // use it

Keep in mind, lua_topointer will return a pointer to whatever you
passed into the function from the lua side.  so if you passed a
pointer to begin with - e.g."Buffer*") - you'll actually get
a double pointer (Buffer**) back.