local f = io.open("C:\\global_all.txt", "w") if not f then f = io.open("D:\\global_all.txt", "w") end if not f then return end
for k, v in pairs(_G) do if type(v) == "table" or type(v) == "userdata" then f:write("--- " .. k .. " ---\n") local ok, t = pcall(function() return pairs(v) end) if ok then for kk, vv in pairs(v) do local ok2, val = pcall(function() return tostring(vv) end) if ok2 then f:write(string.format(" %s = %s\n", tostring(kk), tostring(vv))) end end end end end
-- 1. 如果是 table,直接 pairs if type(obj) == "table" then writeLine("\n[直接 table 遍历]") for k, v in pairs(obj) do writeLine("%s = %s (type: %s)", tostring(k), tostring(v), type(v)) end end
-- 2. 检查元表 local mt = getmetatable(obj) if mt then writeLine("\n[元表存在]") writeLine("__index 类型: %s", type(mt.__index))
if type(mt.__index) == "table" then writeLine("\n[元表 __index 表遍历]") for k, v in pairs(mt.__index) do writeLine("%s = %s (type: %s)", tostring(k), tostring(v), type(v)) end elseif type(mt.__index) == "function" then writeLine("\n[__index 是函数,尝试提取上值]") local i = 1 while true do local name, val = debug.getupvalue(mt.__index, i) if not name then break end writeLine("upvalue %d: %s = %s (type: %s)", i, name, tostring(val), type(val)) -- 如果上值是 table,也直接展开 if type(val) == "table" then writeLine(" --> 展开该上值表:") for kk, vv in pairs(val) do writeLine(" %s = %s (type: %s)", tostring(kk), tostring(vv), type(vv)) end end i = i + 1 end end
-- 3. 其他元方法也可能存有信息(如 __pairs 可能重定义遍历行为) if mt.__pairs then writeLine("\n[元方法 __pairs 存在,尝试调用]") local ok, iter, state, start = pcall(mt.__pairs, obj) if ok then for k, v in iter, state, start do writeLine("%s = %s (type: %s)", tostring(k), tostring(v), type(v)) end end end end
-- 4. 如果是 userdata,尝试 uservalue (Lua 5.2+) if type(obj) == "userdata" then local ok, uv = pcall(debug.getuservalue, obj) if ok and type(uv) == "table" then writeLine("\n[uservalue 表遍历]") for k, v in pairs(uv) do writeLine("%s = %s (type: %s)", tostring(k), tostring(v), type(v)) end end end