This is really weird

my friend wrote something really weird and i dont understand why this works

local test1 = script.Parent.Touched:Connect(
function()
print("no")
end)

shouldnt this be impossible? i always thought it just defines something and it doesnt actually do it, can some one please explain

3 Likes

I think it is magic my friend, I am really not sure.

1 Like
function Function()
    print("no")
end)

local test1 = script.Parent.Touched:Connect(Function)

if the code I gave works, it is self explanatory to why the code you gave works as well

3 Likes

Ill break it down for you if you don’t understand it then.

-- Entire code
local test1 = script.Parent.Touched:Connect(function()
    print("no")
end)

scipt?Parent.Touched is a RBXScriptSignal. It is an event which is fired everytime the part it touched.

RBXScriptSignal has a function called Connect which returns a RBXScriptConnection you also have to pass in a function as the argument

Touched:Connect(<insert function here>) -- Returns a Connection

To read more on the subjects I highly recommend you go to the devhub and search the terms in as you get a much better way of understanding how events work.

The value stored in the variable is a RBXScriptConnection. It can be disconnected if it is no longer needed.

test1:Disconnect()
2 Likes

Functions don’t need names. If you’re using one as a parameter, you can define it inside the parentheses. That’s what your friend did here.

It’s like how you wouldn’t need to say

local text = "Hello world!"
print(text)

And can just say

print("Hello world!")
1 Like

scripts still work even if they are layed out funny

2 Likes

Screenshot 2021-07-18 03.48.01
the problem is the “local” i dont understand how the script runs and prints even though its not told to?

i mean doesnt it mean we just give it a variable and then leave it, why does it still run.

It prints when the part is touched, which is what this code is saying to do.

my point is that it is inside a variable

Yes, Connect is a method that returns something so you can put it in a variable. @koziahss explained that

actualy i didnt have end. its ) not end)

local test1 = script.Parent.Touched:Connect(
function()
print(“no”)
)

i also used it to make a brick become unanchored on touch.

This is a similar concept to cloning.

If you’ve ever seen a clone script, people write this:

local Source = workspace.Source

local CopyOfSource = Source:Clone()

CopyOfSource.Parent = workspace.SomeOtherPlaceHere

functions and events can run inside variables, so that explains why this works in a nutshell.

1 Like