Problems with tables

Achievement:
Have a script change a value in ReplicatedStorage whenever a Enemy is added into a folder (using tables).

Issue:
Everytime an enemy dies, it shows this as the error
“Workspace.Scripts.Script:15: invalid argument #2 to ‘remove’ (number expected, got Instance)”.

Attempted Solutions:
Trying to change the amount of time till the Enemy gets destroyed inside of a different script, just changed the Error time

Code:

--// Variables
local Folder = workspace.Enemies
local EnemyTable = {}
local EnemyAmount = game:GetService("ReplicatedStorage").GamePlayFiles.EnemyAmount

--// Adding Enemy
Folder.ChildAdded:Connect(function(enemy)
	table.insert(EnemyTable, enemy)
	EnemyAmount.Value = #EnemyTable
end)

--// Removing Enemy
Folder.ChildRemoved:Connect(function(enemy)
	table.remove(EnemyTable, enemy)
	EnemyAmount.Value = #EnemyTable
end)

Thanks to anyone who helped!

enemy is not even a number, you have to put the index of the enemy in the table.remove line

Here we get the index of the enemy, then remove it with the index we found.

local enemyIndex = table.find(EnemyTable,enemy)
if enemyIndex then
	table.remove(EnemyTable,enemyIndex)
end

table.remove(Table, table.find(Table, Value))

The only issue why I did it that way, is because it could result in an error if the enemy doesn’t exist in the table, that’s why I checked if the index was nil before removing.

1 Like

table.remove(Table, nil) doesn’t error.

local Value = table.remove(Table, table.find(Table, Value))
if Value then --Validate that a table entry was removed.