Skip to content

Instantly share code, notes, and snippets.

@neomantra
Last active August 29, 2015 13:56
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/9281334 to your computer and use it in GitHub Desktop.
Save neomantra/9281334 to your computer and use it in GitHub Desktop.
FFI serializer fake metamethod
$ luajit ~/Desktop/serialize_metamethod.lua
2 =%= 3
cdata<struct 98>: 0x0004d738
local ffi = require 'ffi'
local Foo_t = ffi.metatype( ffi.typeof('struct { int a, b; }'), {
__index = {
-- return "a =%= b"
_serialize = function( self )
return self.a .. ' =%= ' .. self.b
end,
}
})
local Bar_t = ffi.typeof('struct { int c, d; }')
-- just do tostring and write to file
local function default_serializer( obj )
return tostring(obj)
end
local function serialize( obj )
local success, serializer = pcall(function() return obj._serialize end)
if success then
return serializer( obj )
elseif default_serializer then
return default_serializer( obj )
else
return 'no serializer'
end
end
-- added loop to get trace compiler output
for i = 0, 1000 do
for _, v in ipairs{ Foo_t(2,3), Bar_t(2,3) } do
io.stdout:write( 'ser:', serialize(v), '\n' )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment