Re: A way to associate a Lua value with a FFI pointer?

  • From: Geoff Leyland <geoff_leyland@xxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 9 Apr 2014 21:13:33 +1200

On 9/04/2014, at 8:54 pm, Daniel Kolesa <quaker66@xxxxxxxxx> wrote:

> I would like to know if there is any way to associate a generic Lua value 
> with a FFI pointer.

Would a metatable on the c type help?  Something like this:

ffi = require"ffi"

ffi.cdef"struct A { int x; };"

data = setmetatable({}, { __mode = "k" })

ffi.metatype("struct A", {
  __index = function(a, key) if not data[a] then data[a] = {} end return 
data[a].key end,
  __newindex = function(a, key, value) if not data[a] then data[a] = {} end 
data[a].key = value end,
})

a = ffi.new"struct A"

a.newkey = 1
print(a.newkey)


Other related posts: