Pairs() loop not including things after a small change

So I started making a Vehicle Raycast suspension system cause why not. Now I wanted to keep the system flexible, to later transfer it from a server script to a module script I can reuse. First I made a pairs() loop to find the wheel positions, (i used a variable) after realizing, the game wont know which is which i used the names of the attachments. After that slight change it only includes 2 out of 4 Attachments. I dont know what im doing wrong (I want to work more and more with pairs or ipairs() loops, which one would fit this situation better actually?)
here is the simple loop provided:

local car = workspace:FindFirstChild("Car")
local RunService = game:GetService("RunService")

local WheelPositions = {}

for i, v in pairs(car:GetChildren()) do
	if v:IsA("Attachment") then
		warn(v.Position)
		WheelPositions[v.Name] = v.Position
	end
end
1 Like

If you want to use the name of the attachments, make sure that the names are unique. You’re making WheelPositions a dictionary and it cannot contain duplicate keys. If you try to set a key that already exists, it will overwrite the previous entry.

As for your question about pairs versus ipairs, both are used for iterating through tables, but with the key difference that ipairs is used for arrays with numeric keys. ipairs will start at key = 1, and increment that key until tbl[key] == nil. This means that ipairs will not work for dictionary tables (such as your WheelPositions table), but will work for arrays (such as anything using :GetChildren()). pairs is guaranteed to get every key, value pair, but will not necessarily do so in order.

Personally, I rarely use ipairs over pairs, as ipairs only has any benefit if you absolutely know the order of the table and want to loop through it in that specific order. For example, :GetChildren() does not necessarily return the Instance’s children in the same order every time, so relying on ipairs will not work in that use case.

I might have forgotten to rename 2 attachments, thanks for the detailed reply. You reminded me to double check

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