Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Keeping track of when any data is collected by lua's garbage collection
- -- Only works for Lua version 5.1 as newproxy was removed in Lua 5.2
- -- How this works:
- -- Lua only calls the __gc metamethod for userdata values. This is because
- -- C should be handling the destruction of userdata as Lua doesn't know how.
- -- By using newproxy we can create our own userdata then append it to the
- -- values metatable using debug.setmetatable (which allows one to set the
- -- metatable of any type, not just tables). The idea is that when the object
- -- is deleted, the metatable will be deleted as well, thus calling the __gc
- -- metamethod.
- -- In this example, I will show how one can do just this. Keep in mind if
- -- you want to give the value a metatable you must keep the __userData metamethod.
- -- Also note the __userData metamethod is NOT a real metamethod.
- local table = {};
- local function newUserdata(parent, key, value)
- -- Create a new userdata
- -- Takes a boolean argument to give it a metatable
- -- initially, but I won't add that just to make the
- -- example clearer.
- local userdata = newproxy();
- -- Set the metatable to an empty table.
- debug.setmetatable(userdata, {});
- -- Get the metatable that was just made.
- local udmeta = debug.getmetatable(userdata);
- -- Give it a __gc metatable which will be called
- -- when it is destoryed
- udmeta.__gc = function(ud)
- print("trashed:", ud, parent, key, value);
- end
- return userdata;
- end
- setmetatable(table,
- {
- -- When a new key is added to the table this will be called
- __newindex = function(tab, key, value)
- -- Set 'values' metatable and append a metamethod containing the userdata
- debug.setmetatable(value, {__userData = newUserdata(tab, key, value)});
- rawset(tab, key, value);
- end,
- }
- );
- table["example_key"] = "example_value";
- print("test:", table["example_key"]);
- -- prints: "test: example_value"
- print("collecting", collectgarbage("collect"));
- -- After running the file twice the GC will collect the
- -- previous table and print the following.
- -- "trashed: userdata: 0000 table: 0000 example_key example_value
- -- "collecting 0"
Advertisement
Add Comment
Please, Sign In to add comment