mirror of
https://github.com/SquidDev-CC/CC-Tweaked
synced 2025-01-15 03:35:42 +00:00
Several improvements to textutils.serialise (#920)
- Handle nan and infinity, by emitting them as 0/0 and 0/1. - Differentiate between repeated and recursive tables in the error message.
This commit is contained in:
parent
dc9edf26ec
commit
94ad106272
@ -268,11 +268,16 @@ local g_tLuaKeywords = {
|
||||
["while"] = true,
|
||||
}
|
||||
|
||||
local serialize_infinity = math.huge
|
||||
local function serialize_impl(t, tracking, indent, opts)
|
||||
local sType = type(t)
|
||||
if sType == "table" then
|
||||
if tracking[t] ~= nil then
|
||||
error("Cannot serialize table with recursive entries", 0)
|
||||
if tracking[t] == false then
|
||||
error("Cannot serialize table with repeated entries", 0)
|
||||
else
|
||||
error("Cannot serialize table with recursive entries", 0)
|
||||
end
|
||||
end
|
||||
tracking[t] = true
|
||||
|
||||
@ -307,13 +312,28 @@ local function serialize_impl(t, tracking, indent, opts)
|
||||
result = result .. indent .. "}"
|
||||
end
|
||||
|
||||
if opts.allow_repetitions then tracking[t] = nil end
|
||||
if opts.allow_repetitions then
|
||||
tracking[t] = nil
|
||||
else
|
||||
tracking[t] = false
|
||||
end
|
||||
return result
|
||||
|
||||
elseif sType == "string" then
|
||||
return string.format("%q", t)
|
||||
|
||||
elseif sType == "number" or sType == "boolean" or sType == "nil" then
|
||||
elseif sType == "number" then
|
||||
if t ~= t then --nan
|
||||
return "0/0"
|
||||
elseif t == serialize_infinity then
|
||||
return "1/0"
|
||||
elseif t == -serialize_infinity then
|
||||
return "-1/0"
|
||||
else
|
||||
return tostring(t)
|
||||
end
|
||||
|
||||
elseif sType == "boolean" or sType == "nil" then
|
||||
return tostring(t)
|
||||
|
||||
else
|
||||
|
@ -81,14 +81,17 @@ describe("The textutils library", function()
|
||||
it("serialises basic tables", function()
|
||||
expect(textutils.serialise({ 1, 2, 3, a = 1, b = {} }))
|
||||
:eq("{\n 1,\n 2,\n 3,\n a = 1,\n b = {},\n}")
|
||||
|
||||
expect(textutils.serialise({ 0 / 0, 1 / 0, -1 / 0 }))
|
||||
:eq("{\n 0/0,\n 1/0,\n -1/0,\n}")
|
||||
end)
|
||||
|
||||
it("fails on recursive tables", function()
|
||||
it("fails on recursive/repeated tables", function()
|
||||
local rep = {}
|
||||
expect.error(textutils.serialise, { rep, rep }):eq("Cannot serialize table with recursive entries")
|
||||
expect.error(textutils.serialise, { rep, rep }):eq("Cannot serialize table with repeated entries")
|
||||
|
||||
local rep2 = { 1 }
|
||||
expect.error(textutils.serialise, { rep2, rep2 }):eq("Cannot serialize table with recursive entries")
|
||||
expect.error(textutils.serialise, { rep2, rep2 }):eq("Cannot serialize table with repeated entries")
|
||||
|
||||
local recurse = {}
|
||||
recurse[1] = recurse
|
||||
|
Loading…
Reference in New Issue
Block a user