Originally Posted by doofus
5) I tried to use wipe() but it failed because it does not help with tables inside tables.
|
Here's a drycoded example of
table.wipe() that runs recursively and preserves links to nested tables.
Lua Code:
local NestSafeWipe; do-- function NestSafeWipe(tbl)
-- Local References (finds these faster than calling from global)
local pairs=pairs;
local table_insert=table.insert;
local table_remove=table.remove;
local table_wipe=table.wipe;
local type=type;
-- Local Variables (mitigates memory usage if used often)
local SeenTables={};-- Helps keep track of recursion and looped references (don't want to clean what we've alreay cleaned, also prevents infinite loops)
local SavedLinks={};
local TableQueue={};
function NestSafeWipe(tbl)
SeenTables[tbl]=true;-- Mark table as "seen"
table_insert(TableQueue,tbl);-- Add current table to queue (to initiate loop)
repeat
local curtbl=table_remove(TableQueue);-- Fetch from queue (doesn't matter which end)
for key,val in pairs(curtbl) do-- Find nested tables
if type(val)=="table" then
SavedLinks[key]=val;-- Save key and table
if not SeenTables[val] then-- Queue if not "seen"
SeenTables[val]=true;-- Mark as "seen"
table_insert(TableQueue,val);-- Add to queue
end
end
end
table_wipe(curtbl);-- Wipe current table
for key,val in pairs(SavedLinks) do curtbl[key]=val; end-- Restore nested tables
table_wipe(SavedLinks)-- Done with this data
until #TableQueue<=0-- Exits when queue is empty
table_wipe(SeenTables);-- Done with this data
end
end
Note: The outer do...end is used to explicitly define a variable scope to prevent accidental tampering with the function's persistent variables. To allow the function's presence outside this scope, the function prototype is defined immediately preceding it.
Originally Posted by doofus
It also makes the code cumbersome and weird to read.
|
Think of the languages that don't have a GC and require complex memory structures to be allocated and freed manually. "Just run the GC more" is a poor excuse for not optimizing your code.