1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-12-14 12:10:30 +00:00

Ignore metatables in textutils.serialize

Closes #1368
This commit is contained in:
Jonathan Coates 2023-03-15 21:53:47 +00:00
parent 895bc7721a
commit b9e2d0a936
No known key found for this signature in database
GPG Key ID: B9E431FF07C98D06
2 changed files with 18 additions and 2 deletions

View File

@ -296,6 +296,13 @@ local g_tLuaKeywords = {
["while"] = true,
}
--- A version of the ipairs iterator which ignores metamethods
local function inext(tbl, i)
i = (i or 0) + 1
local v = rawget(tbl, i)
if v == nil then return nil else return i, v end
end
local serialize_infinity = math.huge
local function serialize_impl(t, tracking, indent, opts)
local sType = type(t)
@ -322,11 +329,11 @@ local function serialize_impl(t, tracking, indent, opts)
result = open
local seen_keys = {}
for k, v in ipairs(t) do
for k, v in inext, t do
seen_keys[k] = true
result = result .. sub_indent .. serialize_impl(v, tracking, sub_indent, opts) .. comma
end
for k, v in pairs(t) do
for k, v in next, t do
if not seen_keys[k] then
local sEntry
if type(k) == "string" and not g_tLuaKeywords[k] and string.match(k, "^[%a_][%a%d_]*$") then

View File

@ -118,6 +118,15 @@ describe("The textutils library", function()
expect(textutils.serialise({ 1, 2, 3, a = 1, [false] = {} }, { compact = true }))
:eq("{1,2,3,a=1,[false]={},}")
end)
it("ignores metatables", function()
local actual = { "a", true, x = 2 }
expect(textutils.serialise(setmetatable({}, { __index = actual }))):eq("{}")
expect(textutils.serialise(setmetatable({}, { __pairs = function() return pairs(actual) end }))):eq("{}")
expect(textutils.serialise(setmetatable({ 1 }, { __index = actual }))):eq("{\n 1,\n}")
expect(textutils.serialise(setmetatable({ 1 }, { __pairs = function() return pairs(actual) end }))):eq("{\n 1,\n}")
end)
end)
describe("textutils.unserialise", function()