|
I wrote code below to cache read-only table specially for
environment table. ---- immutable multiple inheritance --- retrieve and cache item from base classes local function cache_index(t, k) local val; if not k or type(k) == "number" then return nil
end for _, env in ipairs(t) do val = env[k] if val then rawset(t, k, val) -- cache value return val end end end ---- Readonly inherit from one or more base classes. --- If child is nil, return new class inherit from ... --- ... can be nil, while #child > 1. --- All parameters should be tables. --- child should not has numeric member --- Carefully check dead-loop of multiple inheritance. function inherit_scopes(child, ...) if not child then child = {__mode = "kv"} end local n = select('#', ...) for k = 1, n do child[#child + 1] = select(k, ...); end if #child < 1 then return false, "No base class
found."; end if #child == 1 then return setmetatable(child, {__index =
child[1]}) end return setmetatable(child, {__index = cache_index}) end Regards, Gary From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of Brian Weed Is
there a way to cache/re-use tables automatically behind the scenes? This
is what I want to do: function
foo()
local t = ObjectFactory() – This function returns tables (from a pool of
reusable tables, or new table if pool is empty)
…
-- use ‘t’
… -- When
‘t’ goes out of scope, (i.e. no more refs to it) I want it to
automatically be added back into the pool for re-use. -- ‘t’
may be passed to other functions (or returned from this function), so I
can’t just place it back into the cache manually at the end of this
function. end I
was hoping that when someone wants a “new” object, I could remove
it from the pool of unused objects, and add it to a table of weak references to
“used” objects before I give it to the user. If
there was a way for me to be notified when the object has no more strong refs
to it, I could move it back into the pool (before its actually garbage
collected). It seems that I can’t use __gc to do this, since that
only gets called for userdata (not tables), and may be too late. The
problem I’m trying to solve is that the programmers on this project have
written lots of code that is constantly creating way too many temporary
objects, which bogs down the memory manager (causes low frame rates, and
choppiness). I
would like to solve this problem automatically in one spot, at all possible
(auto cache these objects, and reuse them), so that we don’t have to
modify all the places that cause this. I’m
thinking that maybe this can’t be done. Perhaps there would be too
many side effects to resurrecting the object. Thanks. Brian |