Table.insert() and variable reference issue

I really don’t understand the problem that’s happening it’s like when I was setting a variable to another variable it doesn’t set the variable to the value of the other variable but at his reference …
Here the code :

local TestSelectedParts = {}

local function GetSelectedParts()
	local Target = Mouse.Target
	local Parts = TestSelectedParts
	for v, Part in pairs(workspace:GetDescendants()) do
		if Part:IsA("BasePart") then
			local Position, Visible = Camera:WorldToViewportPoint(Part.Position)
			if Part:FindFirstChild("SelectionBox") and Visible and math.sign(math.sign(Position.X - Mouse.X) * math.sign(Position.X - Origin.X) + math.sign(Position.Y - (Mouse.Y + 36)) * math.sign(Position.Y - Origin.Y)) == -1 then
				table.insert(Parts, Part) --Here it change TestSelectedParts value and Parts value too
			end
		end
	end
	return Parts
end

why not just do

table.insert(TestSelectedParts, Part)

1 Like

Because I’m changing TestSelectedParts in another part of the script :

if UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) then
	TestSelectedParts = LastSelectedParts
else
	TestSelectedParts = {}
end

EDIT : in fact i don’t want to modify TestSelectedParts anywhere except here !

You would probably have to copy all the elements from the TestSelectedParts table into the Parts table, as setting one table to another table will simply “point” to that table, instead of copying all the elements.

You could probably achieve this through a loop which goes through all the elements in the TestSelectedParts table and inserts it in the Parts table.

1 Like

It is crazy cause like 1 hours ago it was working very well …

A few possibilities:

  • You weren’t testing something which affected that table an hour ago
  • You may have changed something without testing it
  • Studio just being broken, try restarting it

If none of those help, you could try the method I mentioned earlier.

1 Like

Thanks you so much I finaly found how to do it !

local function GetSelectedParts()
	local Target = Mouse.Target
	local Parts = table.move(LastSelectedParts, 1, #LastSelectedParts, 1, {})
	table.insert(Parts, Target:FindFirstChild("SelectionBox") and Target or nil)
	for v, Part in pairs(workspace:GetDescendants()) do
		if Part:IsA("BasePart") then
			local Position, Visible = Camera:WorldToViewportPoint(Part.Position)
			if Part:FindFirstChild("SelectionBox") and Visible and math.sign(math.sign(Position.X - Mouse.X) * math.sign(Position.X - Origin.X) + math.sign(Position.Y - (Mouse.Y + 36)) * math.sign(Position.Y - Origin.Y)) == -1 then
				table.insert(Parts, Part)
			end
		end
	end
	return Parts
end

Basically I only move all my table to the other table !

1 Like

I found a better solution, you can basically use table.clone() !

1 Like

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