Last active
December 18, 2018 23:23
-
-
Save edubart/1fb25e47c98df5e507a940780f4a6045 to your computer and use it in GitHub Desktop.
Debug Lua Mem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function debug_refs() | |
local reftable = {} | |
local function trace_refs(o, src, src2, src3) | |
local typ = type(o) | |
if typ == 'number' or typ == 'boolean' or typ == 'string' or typ == 'thread' or typ == 'nil' then return end | |
if o == debug_refs or o == reftable or o == trace_refs then return end | |
if reftable[o] then return end | |
reftable[o] = true | |
if src3 then | |
src = string.format('%s%s%s', src, src2, tostring(src3)) | |
elseif src2 then | |
src = string.format('%s%s', src, src2) | |
end | |
local refs = 0 | |
if typ == 'table' then | |
for k,v in pairs(o) do | |
trace_refs(k, src, ':', tostring(k)) | |
trace_refs(v, src, '.', tostring(k)) | |
refs = refs + 2 | |
end | |
local mt = getmetatable(o) | |
if mt then | |
trace_refs(mt, src, ':mt') | |
end | |
elseif typ == 'userdata' then | |
local mt = getmetatable(o) | |
if mt then | |
trace_refs(mt, src, ':mt') | |
end | |
elseif typ == 'function' then | |
local i = 1 | |
while true do | |
local n, v = debug.getupvalue(o, i) | |
if not n then break end | |
trace_refs(v, src, '.up', i) | |
i = i + 1 | |
refs = refs + 1 | |
end | |
trace_refs(getfenv(o), 'env') | |
end | |
reftable[o] = { src, refs } | |
end | |
trace_refs(_G, '_G') | |
trace_refs(debug.getregistry(), 'registry') | |
for i=0,3 do | |
trace_refs(getfenv(i), 'global env') | |
end | |
local sorted_refs = {} | |
local total_refs = 0 | |
for o,v in pairs(reftable) do | |
table.insert(sorted_refs, {o, v[1], v[2]}) | |
total_refs = total_refs + v[2] | |
end | |
table.sort(sorted_refs, function(a, b) return a[3] > b[3] end) | |
for i=1,100 do | |
local o, src, refs = unpack(sorted_refs[i]) | |
print(string.format('%8d refs\t%s', refs, src)) | |
end | |
print('total refs', total_refs) | |
end | |
debug_refs() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment