The table I insert into a table overwrites the others

I have a table problem but I don’t know how to solve it. When a table I insert with table.insert into another table, the data in my table is overwrite for the inserted data.

image

I tried to clone the table to insert it but it didn’t work.

local Table = {}
local Car = {Color = "Red", Name = "Bugati"}

table.insert(Table, 1, Car)

Car.Color = "Blue"

table.insert(Table, 2, Car)
print(Table)

It is because Car is a global table appended to another table. Hence, if any of its fields get updated, the changes will reflect on the first index aswell.

1 Like

I’m not sure if this is what you mean but the reason both the values change is because the Car variable is a pointer which means that when you change it every single reference of it will change.

To counteract that, you can use table.clone to clone the Car variable and insert it.

1 Like

Try making a function which creates new objects of Cars like this:

type Car = { Color: string, Name: string };
function CreateCar(Color: string, Name: string): (Car)
	return ({
		Color = Color;
		Name = Name;
	});
end;

local Table = {};
table.insert(Table, 1, CreateCar("Red", "Bugati"))
table.insert(Table, 2, CreateCar("Blue", "Bugati"))

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