How would i create a loop for every object in my table?

Basically i am trying to make it so that all items that have been left unidle for 10 seconds get respawned through this script:

local num = 0
local tickT = 0
local db = false

local Models = {
	
	}

local RespawnPos = {
	
	}

--Set up
for i, v in pairs (game.Workspace.Items:GetChildren()) do
	table.insert(Models, i, v)
	table.insert(RespawnPos, i, v.PrimaryPart.Position)
end

--Check
while wait() do
tickT = tickT + 0.03
	for i, v in pairs(Models) do
		if (RespawnPos[i] - v.PrimaryPart.Position).Magnitude > 5 then
			if not v.PrimaryPart:FindFirstChild("IsGrabbed") then
			db = true
			if num >= 10 then
				Respawn(v.PrimaryPart, RespawnPos[i])
				num = 0
			end
			else
				db = false
				num = 0
			end
		else
			if db == false then
			num = 0
			end
		end
	end
	if tickT > 0.99 then
		tickT = 0
		num = num + 1
	end
end

However, it’s only one item PER 10 seconds that is being respawned rather than all items that have been idle for 10 seconds hence I want to make a loop for every object in said table as i think this could be my solution.

The condition of num >= 10, after being satisfied, will respawn 1 item then will be reset back to 0. After that point, for the duration of the for loop, num stays at 0, thus that if statement’s condition is never satisfied again during that loop. So, only that 1 item is respawned. That’s the issue you’ll want to address.

Ahhh yes, i see now. Would you know a way to create a loop for every object in the table since i think that could be my solution

Well I would store the models a bit differently. I’d make it a dictionary, using the model reference as the “key”, and then the value being a table of data for the model. An example of a piece of data could be the last time the model was dropped. Then, you could just continuously iterate through the dictionary, checking the model’s last time dropped and if it was (for example) 10 seconds ago (I’m assuming that is what you mean by being idle), do whatever you want with it (aka respawn).

Ah yeah, i thought of doing that too but to be honest i completely forgot how to do that in a script, im guessing it was something like table.insert(objects, i, object = 0)

(What exactly was the format to do it btw?)

then going through it and doing objects.object = objects.object + 1?

Here’s a little example to setup your dictionary

for i, item in pairs (game.Workspace.Items:GetChildren()) do
    Models[item] = {lastDropTime = tick(), someExtraDataValue = nil}
end

To iterate through it:

for key, val in pairs (Models) do
    ...

end

So with the way I have setup the table, each key in the dictionary is a reference to the model/item, and the key’s value is a table of whatever data you want to attach to it.

Here’s a neat resource to refresh your memory further:

2 Likes

Your method worked! thanks for the help