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:

Typical usage:

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

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 end end
  local function newarray()
    return ffi.gc("void *[10]"), delarray)