local t = {} setmetatable(t, { __gc = function() print'table garbage collected' end }) t = nil
From previous knowledge of garbage collection I assumed __gc would be invoked after a variable's value is changed to prevent memory leaks, however when I use the __gc metamethod it seems to never be invoked.
Any help or conclusion to why this is happening is appreciated.
Lua has an integrated garbage collector, and handles this delicate procedure automatically. I don't see there being too many cases where you'd need (or want) to interact with Lua's GC, unless you're making a compiler or something.
Aside from that, Lua does offer a simple interface for interacting with it's GC in the form of the collectgarbage
function, and of course, the __gc
metamethod. The collectgarbage
function has one optional argument (in standard Lua), which describes what operation it will preform. In ROBLOX's modded version of the language, you're only able to use one variation of the argument which is required. If you'd like to see other options for standard versions, you can read them here. If you'd like to read about ROBLOX's modification of the function, you can click here.
Anyway, the reason I'm mentioning this is because you may find it useful for debugging. You can essentially use collectgarbage
to manually demand a garbage collection cycle, thus having a little more management and awareness of your code.
For __gc
, however, it appears that Lua only invokes this metamethod if it belongs to a userdata value. Since all ROBLOX-related userdata has a locked metatable, the only way to simulate this would be to call the newproxy
function with a true argument, and establish this metamethod to the blank userdata's metatable. Here's an example:
-- Standard Lua example, won't work in ROBLOX's modded version. local d = newproxy(true) -- New userdata local m = getmetatable(d) -- Metatable associated with userdata -- __gc metamethod m.__gc = function() print("Ran GC cycle") end d = nil -- Userdata object is now unreachable (no known references to it) collectgarbage() -- Force run GC cycle
I'd recommend downloading Lua (or maybe use some online compiler) and playing around with different libraries or environmental functions to get the basic idea of how they normally operate before trying it out on ROBLOX, to avoid confusion. Anyway, hope this helped, if you have any further questions let me know.