Helper library for creating and managing pools of objects in Lua.
local pool = require "pool"
local function newObject()
local obj = {
foo = "bar",
reset = function()
print("reset!")
end
}
return obj
end
local objectPool = pool.create(newObject, 32)
local object = objectPool:obtain()
print(object.foo)
objectPool:free(object)
Object pools are useful for objects that are frequently being created and destroyed (for instance, bullets in a game). Using pools in a situation where creating and destroying instances are expensive can offer a performance boost. For more about object pooling, look here.
Naturally, a pool must be created before it can be used.
pool.create(newObjectFunc, numObjects)
: Creates a pool.
newObjectFunc
is a function that must return the object that is to be inserted into the pool.numObjects
is the number of objects that will be immediately added into the pool. By default, this is 16.
Now that a pool has been created, we can take and put back objects from and into the pool.
pool:obtain()
: Obtains an object from the set of currently free objects.
pool:free(object)
: Puts an object back into the pool for later use.
object
is the object to be freed- If the object being freed contains a function named
reset
, it will be called when it is added back into the pool. Use this to reset any values on the object that you don't want sticking around between uses.
The pool of free objects can also be cleared.
pool:clear()
: Clears the free object pool.
Copy/paste pool.lua into your source folder, then use
local pool = require "pool"
wherever you need it.