Hi. I recently learnt about object pooling, although I’m curious to how I would implement it in Lua since there are plenty of tutorials for other languages but not for this. Thanks!
1 Like
I skimmed over a few definitions of what “object pooling” is and I think I have the right idea, but I’m not sure. Correct me if I’m wrong, but it looks like it is just a collection of objects that are used for later to save the performance cost of constructing the object.
I think you should use a dictionary to define all the ‘item types’ within the pool then have those ‘item types’ be an array?
Here is an example:
local Pool = { --// Store our items
["Bullets"] = { --// Bullet Items
},
["Apples"] = { --// Apple Items
},
["Doge"] = { --// Doge Items
}
}
local function GetItem(ItemName) --// Get a pool item
local Items = Pool[ItemName] --// Access the specific items for the pool
local Item = table.remove(Items, #Items) --// Remove the last one from the Pool because we're using it
if (not Item) then --// If no free items are in the Pool then create a new one
--// Implement constructing logic for the specific Item;
--// Perhaps always save an 'extra' item in the pool that cant be taken from, and clone it when its needed.
end
return Item --// return our Item
end
local function DiscardItem(ItemName, Item) --// Function to discard items based on the name and the item itself.
local Items = Pool[ItemName] --// Access the specific items for the pool
table.insert(Items, Item) --// Insert the new free item.
end
local MyApple = GetItem("Apple") --// Instead of making a new apple we grab one that is not being used;
DiscardItem("Apple", MyApple) --// Put it back in our Pool
MyApple = nil --// Dereference the variable in the scope
You could also try looking at these examples I found:
- lua-users wiki: Optimising Garbage Collection (Basically an article on the concept)
- GitHub - treamology/pool.lua: A helper library for creating and managing pools of objects in Lua. (Looks useful; an OOP approach)
- Generic object pool library - LÖVE (Love2D is different but still Lua and the concepts could be easily applicable? Not sure because didn’t download the file to see)
9 Likes