Find all references to an object in Lua

2019-06-22 14:17发布

问题:

I have a memory leak in the Lua part of my application. For whatever reason, my object is not getting deleted when it should (even when I call collectgarbage("collect")). I assume this means I have a dangling reference somewhere.

So how may I obtain a list of where various references to an object reside? For example:

obj = MyObject()
ref = obj
tbl = {obj}
obj = nil
print(getreferences(obj)) -- should print something like _G.ref, _G.tbl[1]

I would simply write my own function for this, but it would not be able to find references contained inside of closures. Any advice?

回答1:

There's a tool to traverse the whole Lua universe. See http://lua-users.org/lists/lua-l/2006-07/msg00110.html