Need guidance on table efficiency

Hello guys,
I am trying to remove a player from a table. I want to know whether this method is an efficient way to do it.

function module:RemovePlayerFromTable(tableName, player)
	if table.find(tableName, player) then
		for i, v in pairs(tableName) do
			if v == player then
				table.remove(tableName, i)
				print(v) -- Prints out the player who got removed from the table.
			end
		end
		
		print(tableName) -- Prints out the overall players left in the table.
	end
end

wouldn’t it be easier to use table.find ?

table.remove(yourtable, table.find(yourtable, player))

Not sure, but I think that should work no?

Just a small caveat. If table.find() returns nil, the last player in the table is going to get removed.

local index = table.find(tableName, player)
if index then
	table.remove(tableName, index)
end

Worth noting that table.remove() with table.find() only removes the first occurance. The loop (if you don’t break it) removes all occurances. If that was the intention then it’s alright as it is, except you can remove pairs for generalized iteration (for i,v in table do … end).

True!

I was definitely lazy and just put something together without thinking it through, my bad!. Thank you for correcting my mistake!

Hello FellowMeerkat,
Thank you for your response. I see what you mean by if this table.find(tableName, player) returns nil it will remove the last player in the table.

From your code example, I can tell that you are returning what value is in here table.find(tableName, player) then store the returned value to index and then you are checking whether the index is true then remove the index which is the player index or position.

Result in modifying to this code
Code

function module:RemovePlayerFromTable(tableName, player)
	local index = table.find(tableName, player)
	
	if index then
		table.remove(tableName, index)
		print(player.Name.." ("..index..")".." removed")
		print(tableName)
	end
end

The top logs will be the players adding to the table via (playerAdded) event. The bottom logs will be the players removing from the table via (playerRemoving) event. I had no idea that table.find(tableName, player) can return a value of the index. I always use for i,v in pairs(tableName). Thanks for the help. Both solutions work but your solution is better!

Output

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.