Good example by pgimeno.
Personally, I would change the code a little bit:
Code: Select all
local pool = {}
local active = {}
-- initialize pool
for i = 1, 100 do
table.insert(pool, {})
end
local function activate(x, y)
local t = table.remove(pool) or {}
-- re-initialize
t.x = x
t.y = y
-- activate
table.insert(active, t)
return t
end
local function deactivate(t)
for i = 1, #active do
if active[i] == t then
table.remove(active, i)
table.insert(pool, t)
break
end
end
end
The idea being - take the last element from the pool and re-initialize its values.
PS. This approach is useful when you need to activate a lot of objects (such as particles) at once.
math.random(#mansPool)
Just be careful since math.random will raise an error when #mansPool == 0.
second poll objects are active, inactive
Seems like one pool of inactive objects should be enough.