Skip to content

Instantly share code, notes, and snippets.

@DarkWiiPlayer
Last active May 17, 2019 20:51
Show Gist options
  • Save DarkWiiPlayer/c40778a4b2716c516f43b1b96d6188ae to your computer and use it in GitHub Desktop.
Save DarkWiiPlayer/c40778a4b2716c516f43b1b96d6188ae to your computer and use it in GitHub Desktop.
Lua Pool
--- An abstract implementation of an object pool
-- @usage
-- local pool = require("pool"){
-- initialize = function(elem) elem.name = "John Doe"; return elem end;
-- max = 50;
-- }
-- local elem = pool:get() -- Creates a new element because pool is empty
-- print(elem.x) --> John Doe -- pool:put(elem) -- Puts element back into pool --- You know, the thing that this is all about, the pool class -- @type pool
local math = require "math"
local insert, remove =
table.insert,
table.remove
local pool = {
--- A callback that creates a new object.
-- The default function creates an empty Lua table.
-- @callback create
create = function() return {} end;
--- A function that initializes a new object.
-- This gets called every time an object is retrieved or when a new object is created.
-- @callback initialize
initialize = function() end;
--- A function that clears an object upon returning it.
-- @callback clear
clear = function() end;
--- Maximum number of elements to hold at any given moment.
-- When full, extra elements get thrown away.
-- @field max
max = 100;
}
local meta = {__index=pool}
--- Retrieves an element from the pool.
-- If the pool is empty, a new element is created.
-- Parameters are passed to the `initialize` function.
-- @param ... Arguments to pass to `initialize`
-- @return object An object from the top of the pool.
function pool:get(...)
local item
if #self > 0 then
item = remove(self)
else
item = self:create()
end
self.initialize(item, ...)
return item
end
--- Returns an object to the pool.
-- If the pool is at its max size, the object is discarded.
-- @param object Object to put back
-- @treturn boolean whether or not the object was put back (not discarded)
function pool:put(object)
if #self >= self.max then
return true
else
insert(self, object)
return false
end
end
return function(self)
return setmetatable(self or {}, meta)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment