Storing values in variable, is it copy?

So variables can store instance or value. but when I store CFrame(or some others), is it copy of original one?

local cfValue = part.CFrame
--is cfValue is copy of part.CFrame?

When you store a specific property of an object to a variable, it’s cached, so in a way, yes.

Depending on how you use them, yes they can be used to store the current properties of that certain variable

But it mostly depends on how you mainly scope (Or organize) them as well

local OldPos = script.Parent.Position --Let's say this property's position is (25, 0, 0)
script.Parent.Position = Vector3.new(0, 50, 0)

print(OldPos) --This is still saved as the old position value from before so it'll print out (25, 0, 0)
script.Parent.Position = Vector3.new(0, 50, 0)
local NewPos = script.Parent.Position --However we flipped this around, so now our new PartPos is (0, 50, 0)

print(NewPos) --This will print as our new position (Or 0, 50, 0) since we set the position first before defining our variable
1 Like

Variables are not duplicated, they are only assigned. This may get a little confusing but I will explain as best as I can.

Imagine the CFrame as a table.

part.CFrame = {x=0, y=0, z=0}
local cfValue = part.CFrame -- This now references the table
part.CFrame.x = 300 -- This updates the table. You can't actually change CFrame.x in Roblox, this is just for example and we are using a table.
print(cfValue.x) --> 300 - Both the variable and Part.CFrame reference the same table
part.CFrame = {x=500, y=100, z=0}
print(cfValue.x) --> 300 - cfValue references the old table, not the variable that held the table.
-- Even though our part has a new CFrame, cfValue refers to the old CFrame.

Now, because CFrames can’t be changed in Roblox after their creation, knowing this won’t really affect anything. Whatever the variable was when you set it is what it is now.

With numbers, strings, and booleans it might be harder to understand, but it’s the same thing.

local a = 5
local b = a
print(b) --> 5
a = 10
print(b) --> 5 - The variable references the original value.

Numbers also can’t be changed in Roblox. Whenever you assign a number or do math, you are creating a new number instead of changing the old one. Since it is a different number, it won’t transfer new data to other variables.

So TL;DR, you never truly copy anything, but unless your variable is a table or an Instance (Player, Part, Script, PointLight, Tool, etc) you won’t really notice. If you do need to copy a table, you can find a quick function that will effectively copy the table so that changes to one do not affect the other.

3 Likes