Added maxnum option to limit the number of elements in tables.

This commit is contained in:
Paul Kulchenko 2013-09-29 14:33:15 -07:00
parent 28d1f0f49d
commit 115b30ea77
3 changed files with 17 additions and 1 deletions

View File

@ -60,6 +60,7 @@ internal function, but set different options by default:
* nocode (true/false) -- disable bytecode serialization for easy comparison
* nohuge (true/false) -- disable checking numbers against undefined and huge values
* maxlevel (number) -- specify max level up to which to expand nested tables
* maxnum (number) -- specify max number of elements in a table
* valignore (table) -- allows to specify a list of values to ignore (as keys)
* keyallow (table) -- allows to specify the list of keys to be serialized. Any keys not in this list are not included in final output (as keys)
* valtypeignore (table) -- allows to specify a list of value *types* to ignore (as keys)
@ -159,6 +160,9 @@ See LICENSE file.
## History
### v0.25 (Sep 29 2013)
- Added `maxnum` option to limit the number of elements in tables.
### v0.24 (Jun 12 2013)
- Fixed an issue with missing numerical keys (fixes #8).
- Fixed an issue with luaffi that returns `getmetatable(ffi.C)` as `true`.

View File

@ -1,4 +1,4 @@
local n, v = "serpent", 0.24 -- (C) 2012-13 Paul Kulchenko; MIT License
local n, v = "serpent", 0.25 -- (C) 2012-13 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
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, cdata = true}
@ -58,6 +58,7 @@ local function s(t, opts)
for key = 1, maxn do table.insert(o, key) end
for key in pairs(t) do if not o[key] or key > maxn then table.insert(o, key) end end
if opts.sortkeys then alphanumsort(o, t, opts.sortkeys) end
if opts.maxnum and #o > opts.maxnum then o[opts.maxnum+1] = nil end
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing

View File

@ -224,4 +224,15 @@ do
end
end
-- test maxnum limit
do
local a = {a = {7,6,5,4,3,2,1}, b = {1,2}}
local f = assert(loadstring(serpent.dump(a, {maxnum = 3})),
"serializing table with numerical keys: failed")
local _a = f()
assert(#_a.a == 3, "table with maxnum=3 has no more than 3 elements 1/3: failed")
assert(_a.a[3] == 5, "table with maxnum=3 has no more than 3 elements 2/3: failed")
assert(#_a.b == 2, "table with maxnum=3 has no more than 3 elements 3/3: failed")
end
print("All tests passed.")