Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why doesn't this object change its position?

Asked by 5 years ago
Edited 5 years ago
local click = script.Parent
local part = click.Parent

click.MouseClick:Connect(function()
    game.ServerStorage.Handle:Clone().Parent=workspace
end)

local handle = workspace:WaitForChild("Handle")
local pos = handle.Position

handle.CFrame = CFrame.new(pos)

I have made this script that is supposed to spawn a cup in and set its position to the center of a specified brick. However, when I do this, the cup does spawn, however it is in the same place, and doesn't change position. What am I doing wrong here?

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

The problem lies in the fact that you wrongly assume that the pos variable is a reference to the actual property of the Handle. If the position of the Handle changes, the variables you have defined won't update; only its Position property will change. In order to fix this, you can remove the pos variable and only make direct accesses to the Position property of the Handle. You could also modify the variables to hold the Handle object itself, which you have already done, so simply directly access the property.

local click = script.Parent
local part = click.Parent

click.MouseClick:Connect(function()
    game.ServerStorage.Handle:Clone().Parent=workspace
end)

local handle = workspace:WaitForChild("Handle")
handle.CFrame = CFrame.new(handle.Position)

Reference vs Value

It is important to note the difference between a reference and a value. You can think of a reference as holding an actual memory location whilst a value just holds normal information (for example, a boolean).

Reference

In Lua, for example, dictionaries are passed by reference.

local t1 = {
    foo = "abc", 
    bar = 123, 
    foobar = true
}

local t2 = {
    foo = "abc", 
    bar = 123, 
    foobar = true
}

local t1reference = t1
--t1 & t1reference are the same dictionary now, but t2 is different 

t1.foo = "Hello world!"
print(t1.foo) --> Hello world!
print(t1reference.foo) --> Hello world!

print(t2.foo) --> abc

The t1 and t1reference variables both hold the same exact dictionary, whilst t2 is a different dictionary despite it holds the same values.

Value

However, data like booleans and numbers are passed via value.

local number = 50 
local numberVal = num

number = 25
print(number) --> 25
print(numberValue) --> 50

local bool1 = false
local bool1Val = bool1
bool1 = true
print(bool1) --> true
print(bool1Val) --> false 

Even though numberValue was set to number, both variables have different memory and so changing one value does not change the other value. Same for the boolean values, bool1Val never changed even after updating bool1.

Ad

Answer this question