Could this function cause a memory leak?

So in my almost all of my projects, untracked memory linearly or exponentially climbs over time. I suspect this is due to memory leaks/connects in my functions that are causing this. I do know that Untracked memory usage can be almost completely removed as I’ve seen this in almost all of the front page games.

Now, I have lots of loops like this in many of my projects. I’m not too experienced with entirely eradicating memory leaks, I’m sure my code is to blame.

Can you see any immediate problems with this function?

local function getsurvivors()
	local surivors = {}
	for i, player in pairs(game.Players:GetPlayers()) do
		if player.Team == game.Teams.Survivors then
			if player.Character ~= nil then
				if player.Character.Humanoid.Health > 0 then
					table.insert(surivors, player.Character.Head)
	return surivors
1 Like

That function by itself won’t cause any memory leaks. All you’re doing is searching through Players, checking a team, adding them to a table and returning that. Do you have an example of how you’re using that function?

I would recommend stating your table at the top then clearing the table when your done using it. You can clear a table by simply doing table = {}. Creating new tables overtime will slowly take more and more memory.

There’s been a lot of complaints regarding UntrackedMemory climbing stupidly high over the course of time. Unless you notice any performance issues, I would ignore this for now. One potential issue I could see is that if the survivors table doesn’t have weak keys, you could be experiencing a memory leak. You’ll want to clear that table once you don’t need it anymore.

By the way, a little unrelated, but may I interest you in Team.GetPlayers over iterating through all players and checking their teams?

1 Like

Simply using to fetch a table of player’s head for a spectate system. Function is called every time the spectate GUI is opened.

Thanks for the replies everyone!

that function is incredibly helpful, thanks

I considered doing this, but wasn’t sure if that would correctly make the table weak. I will try it.

Thanks guys

1 Like

Yeah in that case, this function is called so little that you will never see any significant performance impacts at all from just this function.While what @colbert2677 said about UntrackedMemory is definitely true, you should still be constantly searching for things that may impact it.

1 Like