In the ffi documentation, it mentions that " the C type metamethod mechanism is most useful when used in conjunction with C libraries that are written in an object-oriented style. Creators return a pointer to a new instance, and methods take an instance pointer as the first argument. Sometimes you can just point __index to the library namespace and __gc to the destructor and you're done. But often enough you'll want to add convenience wrappers, e.g. to return actual Lua strings or when returning multiple values."
I have a C library that looks like this:
local ffi = require("ffi")
ffi.cdef [[
typedef struct T *T;
T new_t();
void t_set(T t, int value);
int t_get(T t);
void t_free(T t);
]]
I'm binding it in the following way:
local lib = ffi.load("./lib/libtest.so")
local tLib = ffi.metatype("T", {
__index = {
new = lib.new_t,
set = lib.t_set,
get = lib.t_get,
},
__gc = lib.t_free
})
local t1 = tLib.new()
t1:set(10)
t1:get()
t1 = nil
Why doesn't setting t1 to nil invoke the __gc metamethod? Also, is my approach correct for binding opaque C objects?