Created
February 27, 2014 14:35
-
-
Save neomantra/9251273 to your computer and use it in GitHub Desktop.
Exploring accessing metamethods with FFI objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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