tinytoml/spec/decoder.lua
FourierTransformer e72f5c4392
Added encode_datetime_as, removed assign value function, and added type checking for options (#15)
## Changes
- All options are runtime type checked
- Default options now specified in the codebase
- Removed `assign_value_function` (should offer a nice speedup in
regular Lua)
- Modified decoder tests to re-add toml-test tags, so this is no
longer needed
  - NOTE: this does mean that the toml-test fails for non Lua 5.3-5.5.
- Added comparison table to README with other TOML parsers
- Can now specify encoding dates/times as strings _or tables!_
2026-01-09 19:52:20 -06:00

72 lines
1.9 KiB
Lua

local cjson = require("cjson")
local tinytoml = require("tinytoml")
local to_inf_and_beyound = {
["inf"] = true,
["-inf"] = true,
["nan"] = true,
["-nan"] = true,
}
local function float_to_string(x)
if to_inf_and_beyound[tostring(x)] then
return tostring(x)
end
for precision = 15, 17 do
local s = ('%%.%dg'):format(precision):format(x)
if tonumber(s) == x then
return s
end
end
end
local function add_toml_test_tag(table_to_clear)
if type(table_to_clear) ~= "table" then
if type(table_to_clear) == "number" then
if math.type(table_to_clear) == "integer" then
return {type="integer", value=tostring(table_to_clear)}
else
return {type="float", value=float_to_string(table_to_clear)}
end
elseif type(table_to_clear) == "string" then
return {type="string", value=table_to_clear}
elseif type(table_to_clear) == "boolean" then
return {type="bool", value=tostring(table_to_clear)}
else
return table_to_clear["value"]
end
else
if not (table_to_clear.type and table_to_clear.value) then
for k, v in pairs(table_to_clear) do
table_to_clear[k] = add_toml_test_tag(v)
end
end
end
return table_to_clear
end
local type_conversion = {
["datetime"] = function(raw_string) return {type="datetime", value=raw_string} end,
["datetime-local"] = function(raw_string) return {type="datetime-local", value=raw_string} end,
["date-local"] = function(raw_string) return {type="date-local", value=raw_string} end,
["time-local"] = function(raw_string) return {type="time-local", value=raw_string} end,
}
local output = tinytoml.parse(io.read("*a"), { load_from_string = true, encode_datetime_as = "string", type_conversion = type_conversion })
add_toml_test_tag(output)
print(cjson.encode(output))