lunajson icon indicating copy to clipboard operation
lunajson copied to clipboard

Expose encoder dispatcher for modification

Open Ayplow opened this issue 5 years ago • 2 comments

Expose the dispatcher table to allow custom encoding of data types.

Example use case:

local zero_based_meta = {
  __index = function(t, k)
    if type(k) == "number" then
      return t.raw[k + 1]
    end
  end
}
local encode, dispatcher = newencoder()

local f_table = dispatcher.table
function dispatcher.table(o)
  return f_table(getmetatable(o) == zero_based_meta and o.raw or o)
end

local arr = setmetatable({ raw = {3,7,4} }, zero_based_meta)
print(arr[2]) --> 4
print(encode(arr)) --> [3, 7, 4]

Ayplow avatar Aug 05 '19 18:08 Ayplow

Hello, Take care about possible non-numeric key I think about the potential new "n" field.

tst2005 avatar Aug 06 '19 10:08 tst2005

I suppose a broken example doesn't serve its purpose very well. Fixed!

Ayplow avatar Aug 06 '19 19:08 Ayplow