Skip to content

Commit

Permalink
Prevent memory leaks by using metatables as private object storage
Browse files Browse the repository at this point in the history
Signed-off-by: Yan Minari <yangm97@gmail.com>
  • Loading branch information
yangm97 committed Dec 18, 2018
1 parent ad50690 commit 41a822a
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 94 deletions.
19 changes: 10 additions & 9 deletions lua/groupbutler/chat.lua
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
local Chat = {}

local _p = setmetatable({}, {__mode = "k"}) -- weak table storing all private attributes
local function p(self)
return getmetatable(self).__private
end

function Chat:new(obj, update_obj)
_p[obj] = {
api = update_obj.api,
db = update_obj.db,
u = update_obj.u,
}
setmetatable(obj, {__index = self})
function Chat:new(obj, private)
assert(private.db, "Chat: Missing private.db")
setmetatable(obj, {
__index = self,
__private = private,
})
return obj
end

function Chat:cache()
_p[self].db:cacheChat(self)
p(self).db:cacheChat(self)
end

return Chat
19 changes: 10 additions & 9 deletions lua/groupbutler/user.lua
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
local User = {}

local _p = setmetatable({}, {__mode = "k"}) -- weak table storing all private attributes
local function p(self)
return getmetatable(self).__private
end

function User:new(obj, update_obj)
_p[obj] = {
api = update_obj.api,
db = update_obj.db,
u = update_obj.u,
}
setmetatable(obj, {__index = self})
function User:new(obj, private)
assert(private.db, "User: Missing private.db")
setmetatable(obj, {
__index = self,
__private = private,
})
return obj
end

function User:cache()
_p[self].db:cache_user(self)
p(self).db:cache_user(self)
end

return User

0 comments on commit 41a822a

Please sign in to comment.