On Wed, Oct 31, 2012 at 2:33 PM, François Perrad <francois.perrad@xxxxxxxx> wrote: > I try to use some Lua/C functions which are included in the ffi.C namespace. > More especially, I refactore a code which uses C malloc/free, with lua_Alloc. > > local ffi = require "ffi" > ffi.cdef[[ > typedef struct lua_State lua_State; > typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, > size_t nsize); > lua_Alloc lua_getallocf (lua_State *L, void **ud); > ]] > print(ffi.C.lua_getallocf) --> cdata<void *(*())()>: 0x080530d0 > > local ud = ffi.new("void*") > print(ud) --> cdata<void *>: NULL > local alloc = ffi.C.lua_getallocf(L, ud) > local buffer = alloc(ud, 0, 0, 4096) > > but I don't know how to retrieve the current lua_State which is the > first parameter of all Lua/C functions. > > François > The FFI does not provide any way to access the current lua_State, by design [1]. What you may be able to do is create a dummy coroutine and use the thread object for L, but I haven't tried that myself. By the way, assuming you do manage to get a valid L, there is a separate issue with your example code: passing a "void*" value for the 'ud' parameter will not work the way you expect. You should instead do something like this: local out_ud = ffi.new("void*[1]") local alloc = ffi.C.lua_getallocf(L, out_ud) local buffer = alloc(out_ud[0], 0, 0, 4096) [1] http://lua-users.org/lists/lua-l/2011-10/msg01075.html -Duncan