如何在pil4中实现练习15.5?

我正在pil4中完成这个练习。

练习15.5:

避免使用构造函数保存具有循环的表格的方法太过激进了。可以使用构造函数将表格保存在更可读的格式中,然后仅在后期使用赋值来修正共享和循环。使用这种方法重新实现函数 save(图15.3,“保存带循环的表格”)。将您在先前练习中实现的所有好处添加到其中(缩进,记录语法和列表语法)。

我尝试了下面的代码,但似乎无法处理具有字符串键的嵌套表。

local function basicSerialize(o)
    -- 数字或字符串
    return string.format("%q",o)
end

local function save(name,value,saved,indentation,isArray)
    indentation = indentation or 0
    saved = saved or {}
    local t = type(value)
    local space = string.rep(" ",indentation + 2)
    local space2 = string.rep(" ",indentation + 4)
    if not isArray then io.write(name," = ") end
    if t == "number" or t == "string"  or t == "boolean" or t == "nil" then
        io.write(basicSerialize(value),"\n")
    elseif t == "table" then
        if saved[value] then
            io.write(saved[value],"\n")
        else
            if #value > 0 then
                if indentation > 0 then io.write(space) end
                io.write("{\n")
            end
            local indexes = {}
            for i = 1,#value do
                if type(value[i]) ~= "table" then
                    io.write(space2)
                    io.write(basicSerialize(value[i]))
                else
                    local fname = string.format("%s[%s]",name,i)
                    save(fname,value[i],saved,indentation + 2,true)
                end
                io.write(",\n")
                indexes[i] = true
            end
            if #value > 0 then
                if indentation > 0 then io.write(space) end
                io.write("}\n")
            else
                io.write("{}\n")
            end
            saved[value] = name
            for k,v in pairs(value) do
                if not indexes[k] then
                    k = basicSerialize(k)
                    local fname = string.format("%s[%s]",name,k)
                    save(fname,v,saved,indentation + 2)
                    io.write("\n")
                end
            end
        end
    else
        error("无法保存" .. t)
    end
end

local a = { 1,2,3, {"one","Two"} ,5, {4,b = 4,5,6} ,a = "ddd"}
local b = { k = a[4]}
local t = {}
save("a",a,t)
save("b",b,t)
print()

但我得到了错误的输出。

a = { 1, 2, 3, { "one", "Two", } , 5, { 4, 5, 6, } a[6]["b"] = 4 , }

a["a"] = "ddd"

b = {}

b["k"] = a[4]

我该如何使文本'a[6]["b"] = 4'跳出表构造函数?

点赞