lua-users home
lua-l archive

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


Josh Haberman wrote:
> My use case is that I want to expose a refcounted C structure to Lua via
> the FFI.  When Lua no longer needs the structure, I want to unref it
> using a C function.

Good news: you can drop your userdata workarounds now -- I just
added finalizers to cdata objects:

  http://luajit.org/ext_ffi_api.html#ffi_gc

Typical usage:

  local p = ffi.gc(ffi.C.malloc(n), ffi.C.free)
  ...
  p = nil -- Last reference to p is gone.
  -- GC will eventually run finalizer: ffi.C.free(p)

You can also use a Lua function as a finalizer. E.g. for structs
or arrays that need more complex cleanup:

  local function delarray(a)
    for i=0,9 do if a[i] ~= nil then ffi.C.free(a) end end
  end
  local function newarray()
    return ffi.gc(ffi.new("void *[10]"), delarray)
  end

--Mike