Skip to content

Instantly share code, notes, and snippets.

@neomantra
Created February 27, 2014 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neomantra/9251273 to your computer and use it in GitHub Desktop.
Save neomantra/9251273 to your computer and use it in GitHub Desktop.
Exploring accessing metamethods with FFI objects
local ffi = require 'ffi'
local C = ffi.C
-- in reality this would be some hashing library,
-- but for this example they are dumb functions
local hasher = function(x) return tonumber(x) end
local H = {
hash = hasher,
hash_combine = function(seed, v) return seed + hasher(v) end,
}
local Foo_t = ffi.metatype( ffi.typeof('struct { int a, b; }'), {
__hash = function( self )
return H.hash_combine( H.hash(self.a), H.hash(self.b) )
end
})
local Bar_t = ffi.metatype( ffi.typeof('struct { int a, b; }'), {
__index = {
__hash = function( self )
return H.hash_combine( H.hash(self.a), H.hash(self.b) )
end
}
})
local Baz_t = ffi.typeof('struct { int a, b; }')
-- getmetatable returns the string 'ffi' so we can't do anything with it
print( getmetatable(Foo_t()) )
-- prints 'function'
print( type(Bar_t().__hash) )
-- without a metatable with __index, accessing __hash throws an error
print( pcall(function() return type(Baz_t().__hash) end ) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment