q66 / cffi-lua

A portable C FFI for Lua 5.1+
MIT License
176 stars 24 forks source link

Support metatable for ctype #5

Closed vsergeev closed 3 years ago

vsergeev commented 3 years ago

It would be nice to have metatable support for ctypes themselves, as with the LuaJIT FFI:

local ffi = require('cffi')

ffi.cdef[[
typedef struct point {
    int x;
    int y;
} point_t;
]]

local mt = {
    __tostring = function (self)
        return string.format("Point<%d, %d>", self.x, self.y)
    end,
    __index = {
        from_array = function (arr)
            return ffi.new("point_t", arr[1], arr[2])
        end
    }
}

Point = ffi.metatype("point_t", mt)

print(Point(1, 2)) --> Point<1, 2>
print(Point.from_array({3, 4})) --> expected: Point<3, 4>, cffi-lua gives: 'ctype' is not indexable

This allows implementing static methods on the ctype, like alternate constructors, or utility functions namespaced under the ctype.

q66 commented 3 years ago

metatype for ctypes is supported, but it seems this case is not handled, it probably should

vsergeev commented 3 years ago

Awesome, thanks :+1: