目的
为了避免经常申请分配table表,实现个table池,方便复用。
实现
---@class tablePool @表池,避免经常分配
tablePool = {}
local tbPool = {}
---空表
tablePool.EmptyTable = {}
---Get 获取表
---@generic T
---@param tag string
---@param create T @table|function
---@return T
function tablePool.Get(tag, create)
local pool = tbPool[tag]
if not pool then
pool = {}
pool.get = create
pool.func = type(create) ~= 'table'
pool.len = 0
tbPool[tag] = pool
end
local len = pool.len
if len > 0 then
pool.len = len - 1
return pool[len]
end
if pool.func then
return pool.get()
else
return clone(pool.get)
end
end
---Release 释放表,会自动调用其Clear方法
---@param tag string
---@param obj table
function tablePool.Release(tag, obj)
if not obj then
return
end
local pool = tbPool[tag]
if not pool then
return
end
local len = pool.len + 1
pool.len = len
pool[len] = obj
if obj.Clear then
obj:Clear()
end
end
---ArrayClear 数组的清除,数组里简单数据类型,非table池申请
function tablePool.ArrayClear(list)
local count = #list
for i = 1, count do
list[i] = nil
end
end
---ArrayRelease 数组的清除,数组里是table池申请的子表
function tablePool.ArrayRelease(tag, list)
local count = #list
for i = 1, count do
tablePool.Release(tag, list[i])
list[i] = nil
end
end
---DictionaryRelease 字典的清除,字典里是table池申请的子表
function tablePool.DictionaryRelease(tag, list)
for k, v in pairs(list) do
tablePool.Release(tag, v)
list[k] = nil
end
end