Skip to content

Commit 6b60f5f

Browse files
committed
feat: add encoding of nil values in tables and of empty objects
1 parent c6bc6a5 commit 6b60f5f

File tree

1 file changed

+31
-19
lines changed

1 file changed

+31
-19
lines changed

msgpack.lua

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,27 @@ local type, pcall, pairs, select = type, pcall, pairs, select
4343
--]]----------------------------------------------------------------------------
4444
local encode_value -- forward declaration
4545

46-
local function is_an_array(value)
46+
local NIL = {} -- unique object to represent nil
47+
48+
local EMPTY_OBJECT = {} -- unique object to represent an empty object
49+
50+
local function is_an_array(value, empty_as_array)
51+
local empty = true
4752
local expected = 1
48-
for k in pairs(value) do
49-
if k ~= expected then
50-
return false
51-
end
52-
expected = expected + 1
53-
end
54-
return true
53+
54+
for k in pairs(value) do
55+
empty = false
56+
if k ~= expected then
57+
return false
58+
end
59+
expected = expected + 1
60+
end
61+
62+
if empty and not empty_as_array then
63+
return false
64+
end
65+
66+
return true
5567
end
5668

5769
local encoder_functions = {
@@ -123,8 +135,9 @@ local encoder_functions = {
123135
end
124136
end
125137
end,
126-
['table'] = function(value)
127-
if is_an_array(value) then -- it seems to be a proper Lua array
138+
['table'] = function(value, empty_as_array)
139+
if empty_as_array == nil then empty_as_array = true end
140+
if is_an_array(value, empty_as_array) then -- it seems to be a proper Lua array
128141
local elements = {}
129142
for i, v in pairs(value) do
130143
elements[i] = encode_value(v)
@@ -158,18 +171,11 @@ local encoder_functions = {
158171
}
159172

160173
encode_value = function(value)
174+
if value == NIL then return encoder_functions['nil']() end
175+
if value == EMPTY_OBJECT then return encoder_functions['table']({}, false) end
161176
return encoder_functions[type(value)](value)
162177
end
163178

164-
local function encode(...)
165-
local data = {}
166-
for i = 1, select('#', ...) do
167-
data[#data + 1] = encode_value(select(i, ...))
168-
end
169-
return tconcat(data)
170-
end
171-
172-
173179
--[[----------------------------------------------------------------------------
174180
175181
Decoder
@@ -368,6 +374,12 @@ return {
368374
return nil, 'cannot decode MessagePack'
369375
end
370376
end,
377+
378+
--- an object that is packed as a nil value
379+
NIL = NIL,
380+
381+
--- an object that is packed as an empty object
382+
EMPTY_OBJECT = EMPTY_OBJECT
371383
}
372384

373385
--[[----------------------------------------------------------------------------

0 commit comments

Comments
 (0)