1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-10-01 08:20:47 +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:
Wojbie 2021-09-17 11:30:23 +02:00 committed by GitHub
parent dc9edf26ec
commit 94ad106272
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 6 deletions

View File

@ -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

View File

@ -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