Remove Seats every Round

I’m currently working on a Minigame with 30 seats. Every round, 3 seats disappear. All seats are in a model called ‘Seats’ and are models themselves. They are numbered from 1 to 30 (Seat1,Seat2…,Seat30). This is the script I used to remove 3 Seats every round:

local function RemoveSeats()
	local availableSeats = {}
		
	for i,Seat in pairs(Seats:GetChildren()) do
		if Seat:IsA("Model") then
			table.insert(availableSeats,i,Seat)
		end
	end
	
	for i = 1,3 do
		local RandomNumber = math.random(1,#availableSeats)
		local Seat = availableSeats[RandomNumber]
		Seat:Destroy()
		table.remove(availableSeats,RandomNumber)
	end
end

while wait(10) do
    RemoveSeats()
end

Why, however, it does not remove the destroyed seats from the table every time and this error occurs:
attempt to index local 'Seat' (a nil value)
in the line where I call Seat:Destroy()

Why and is this a good way to achieve what I want?

Thanks in advance :slight_smile:

1 Like

Just adding a check to see if the object exists would solve your problems.

	for i = 1,3 do
		local RandomNumber = math.random(1,#availableSeats)
		local Seat = availableSeats[RandomNumber]
		if Seat then
			Seat:Destroy()
			table.remove(availableSeats,RandomNumber)
		end
	end

If it doesnt exist only 2 or less Seatswould be removed and thats not what I want. And why are there nil values? Did I make a mistake in logic?

This solution works:

local availableSeats = {}

local loc = 0
	
for i,Seat in pairs(Seats:GetChildren()) do
	if Seat:IsA("Model") then
		availableSeats[loc] = Seat
		loc = loc + 1
	end
end

for i = 1,3 do
	local RandomNumber = math.random(1,#availableSeats)
	local Seat = availableSeats[RandomNumber]
	Seat:Destroy()
	table.remove(availableSeats,RandomNumber)
end

Personally, I avoid table.insert since it is more confusing to me. I added the variable loc to place each variable in the table so I know that it’s there when I want to grab from it latter. It also reduces the possibility of empty indexes.

You don’t need to give i in table.insert.

As dumb as it is, he’s right. Now it works perfectly.

1 Like