打印四级 _G

发表于:2025-7-23 06:07:31 44

local file = io.open("lllll.txt", "w")
if not file then
print("无法创建文件 lllll.txt")
return
end

-- 判断是否跳过键(如果是数字或包含数字则跳过)
local function shouldSkipKey(k)
return type(k) == "number" or (type(k) == "string" and string.match(k, "%d"))
end

-- JSON 风格格式化
local function formatValue(v)
if type(v) == "string" then
return '"' .. v .. '"'
else
return tostring(v)
end
end

-- 递归遍历表并生成 JSON 风格输出
local function dumpTable(t, depth, maxDepth)
if depth > maxDepth then
file:write("{}")
return
end

file:write("{\n")
local isFirst = true

for k, v in pairs(t) do
    if not shouldSkipKey(k) then
        if not isFirst then
            file:write(",\n")
        end
        isFirst = false

        -- 缩进
        file:write(string.rep("    ", depth))

        -- 键
        if type(k) == "string" then
            file:write('"' .. k .. '": ')
        else
            file:write(tostring(k) .. ": ")
        end

        -- 值
        if type(v) == "table" then
            -- 标记层级(仅用于调试,正式输出可删除)
            file:write("-- [")
            if depth == 1 then file:write("一级表")
            elseif depth == 2 then file:write("二级表")
            elseif depth == 3 then file:write("三级表")
            elseif depth == 4 then file:write("四级表")
            else file:write(tostring(depth) .. "级表") end
            file:write("]\n" .. string.rep("    ", depth))

            dumpTable(v, depth + 1, maxDepth)
        else
            file:write(formatValue(v))
        end
    end
end

file:write("\n" .. string.rep("    ", depth - 1) .. "}")

end

-- 遍历 _G 并写入文件
file:write("{\n")
for key, value in pairs(_G) do
if type(value) == "table" and not shouldSkipKey(key) then
file:write(' "' .. tostring(key) .. '": -- [一级表]\n ')
dumpTable(value, 2, 4) -- 最大深度 4 级
file:write(",\n")
end
end
file:write("}\n")

file:close()
print("完成")

收藏
送赞
分享

发表回复