For i, v in next, CollectionService:GetTagged() do Iterates through Entire Table

When I do:

print("Clicked!")
for i, Model in next, CollectionService:GetTagged("Targetable") do
	print(i)
end

It prints 4 times as I have 4 Targetable dummies in workspace.

But when i do:

print("Clicked!")
for i, Model in next, workspace:GetChildren() do
	print(i)
end

It prints only one time getting the next item in the iteration instead of looping through the entire table.

Why is it looping through entire table when I use next with CollectionService:GetTagged()? Shouldn’t it only print(i) once? The print(“Clicked!”) only prints one time so I know I’m not calling the for i, v in next loop 4 times in a row!

Is this a bug? I couldn’t find anything related to this issue on the DevForums.

3 Likes

Can you show a screenshot of what you have in the Workspace during runtime? Or when you click it as I assume by the print statement.

Oh shoot now that I’m testing it again after doing:

for i, Model in next, workspace:GetChildren() do
	print(i)
end

It prints(1 2 3 4 5 6 7 8), the number of children in the workspace. That’s weird I thought next only runs one time down and doesn’t loop through all children. I’m not sure why it only printed(1) the first time I did that!

But I found a solution to what I wanted, just getting one index next in the table:

local TrackIndex


print("Clicked!")
local AllTargetable = CollectionService:GetTagged("Targetable")
local i, Model = next(AllTargetable, TrackIndex)
if i == #AllTargetable then
	TrackIndex = nil
else
	TrackIndex = i
end
print(i, Model)

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