TablePool_Tips.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. ---
  2. --- Generated by EmmyLua(https://github.com/EmmyLua)
  3. --- Created by PZM.
  4. --- DateTime: 2021/10/11 13:16
  5. ---@class TablePool
  6. ---@field list table[]
  7. ---@field isPushNotCheckContain boolean @不填的时候,要保证对象没有__eq操作。填的时候,例如Vector3的对象池,要保证外部不会重复添加,不然Pop出来的数据可能是同一个
  8. TablePool = class()
  9. local this = TablePool
  10. function this:ctor(isPushNotCheckContain)
  11. self.isPushNotCheckContain = isPushNotCheckContain
  12. self.list = {}
  13. end
  14. ---@return table @type 和 data不填,返回{}表
  15. ---@param t table @类型名
  16. ---@param ctorData any @构造函数参数
  17. function this:Pop(t, ctorData, isPopFirst)
  18. local count =self:Count()
  19. if count == 0 then
  20. return t and t(ctorData) or {},true
  21. end
  22. return table.remove(self.list, isPopFirst and 1 or count),false
  23. end
  24. function this:PopByCondition(t,data,func)
  25. for k, v in pairs(self.list) do
  26. if func and func(v) then
  27. return table.remove(self.list,k)
  28. end
  29. end
  30. return t and t(data) or {}
  31. end
  32. function this:Count()
  33. return #self.list
  34. end
  35. function this:Foreach(func)
  36. for k, v in pairs(self.list) do
  37. if func then
  38. func(v)
  39. end
  40. end
  41. end
  42. ---@param t table @Pop返回的对象
  43. ---@param isPushFirstPos boolean @是否放入第一个位置
  44. ---@return boolean @是否 push 成功,重复的不添加
  45. function this:Push(t,isPushFirstPos)
  46. --外部多次添加一个对象,table.contains可能会引起重载_eq对象或者数据量大的遍历消耗
  47. if not self.isPushNotCheckContain then
  48. if table.contains(self.list,t) then
  49. --logError('重复添加,数据会异常,保证调用Push后置空')
  50. return false
  51. end
  52. end
  53. if isPushFirstPos then
  54. table.insert(self.list,1,t)
  55. else
  56. table.insert(self.list,t)
  57. end
  58. return true
  59. end
  60. function this:Clear()
  61. if self:Count()==0 then
  62. return
  63. end
  64. table.clear(self.list)
  65. end
  66. function this:Release()
  67. self.list = {}
  68. end
  69. function this:PushIncludeSubTable(t,isPushFirstPos,isClear)
  70. if type(t)~='table' then
  71. return
  72. end
  73. for k, v in pairs(t) do
  74. self:PushIncludeSubTable(v,isPushFirstPos,isClear)
  75. end
  76. if isClear then
  77. table.clear(t)
  78. end
  79. self:Push(t,isPushFirstPos)
  80. end