diff --git a/README.md b/README.md index 6800c12..ef5a3cf 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,10 @@ See LICENSE file. ## History +Nov 16 2012 v0.19 + - Fixed an issue with serializing shared functions as keys. + - Added serialization of metatables using __tostring (when present). + Sep 13 2012 v0.18 - Fixed an issue with serializing data structures with circular references that require emitting temporary variables. - Fixed an issue with serializing keys pointing to shared references. diff --git a/src/serpent.lua b/src/serpent.lua index c68f88e..cd18081 100644 --- a/src/serpent.lua +++ b/src/serpent.lua @@ -1,4 +1,4 @@ -local n, v = "serpent", 0.18 -- (C) 2012 Paul Kulchenko; MIT License +local n, v = "serpent", 0.19 -- (C) 2012 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Serializer and pretty printer of Lua data types" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true} @@ -57,6 +57,8 @@ local function s(t, opts) elseif ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath -- set path to use as reference + if getmetatable(t) and getmetatable(t).__tostring + then return tag..safestr(tostring(t))..comment("meta",l) end if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = #t, {}, {} for key = 1, maxn do table.insert(o, key) end diff --git a/t/test.lua b/t/test.lua index ad3d98f..2106bee 100644 --- a/t/test.lua +++ b/t/test.lua @@ -96,7 +96,6 @@ do local tbl = {'tbl'} a[3] = {[{}] = {happy = tbl}, sad = tbl} - print(serpent.dump(a, {sparse = false, nocode = true})) assert(loadstring(serpent.dump(a, {sparse = false, nocode = true})), "table as key with circular/shared reference: failed") end @@ -108,9 +107,19 @@ do a.a[function1]=function() end a.b=a.a[function1] - print(serpent.dump(a, {sparse = false, nocode = true})) assert(loadstring(serpent.dump(a, {sparse = false, nocode = true})), "functions as shared references while processing shared refs: failed") end +-- test serialization of metatable with __tostring +do + local mt = {} + mt.__tostring = function(t) return 'table with ' .. #t .. ' entries' end + local a = {'a', 'b'} + setmetatable(a, mt) + + assert(loadstring(serpent.dump(a, {sparse = false, nocode = true, comment = true})), + "metatable with __tostring serialized with a comment: failed") +end + print("All tests passed.")