Last active
August 29, 2015 13:56
-
-
Save neomantra/9281334 to your computer and use it in GitHub Desktop.
FFI serializer fake metamethod
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
$ luajit ~/Desktop/serialize_metamethod.lua | |
2 =%= 3 | |
cdata<struct 98>: 0x0004d738 |
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 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