Ad
Log in to vote
0

Why do i have to sometimes put a ) at end?

Asked by 7 years ago

Why do i have to sometimes put a ) at end?

2 answers

Log in to vote
5
Answered by
TofuBytes 500 Moderation Voter
7 years ago

Well, there's a difference between end and end). For example, have a while true do function. It will not require a ')' at the end because it is not a function that is uses '()' in general.

while true do
wait(1)
print('Hello world!')
end

But, if we do something like:

script.Parent.Touched:connect(function(hit)
end)

Then, we have a end) because we opened 2 functions and one closed: (hit). We finally close the last function by putting end) at the end of our script.

0
Thanks! iluvmaths1123 198 — 7y
0
You put end) at the end of an anonymous function. Operation_Meme 890 — 6y
Ad
Log in to vote
1
Answered by
adark 5477 Badge of Merit Moderation Voter Community Moderator
7 years ago

wall142 is sorta correct.

When you use end) instead of end, it's because the former is actually the last line of a written-in function. That is, a method (or function) call that takes a function as an argument had that function written into the call, rather than assigned to a variable. These kind of functions are called anonymous functions.

For example, the connect method of ROBLOX events (aka Touched) takes a function as a parameter - the function to be called when the event fires.

function Name(hit)
end

Part.Touched:connect(Name)

Since function Name(hit) is syntactic sugar for Name = function(hit) in Lua, you can put the definition of the function (the actual code) in where the variable that refers to it is placed.

Aka:

Part.Touched:connect(function(hit) end)

Notice, there is a closing parenthesis on this end, and not on the one in my first code block. This parenthesis matches up with the opening parenthesis of the connect method, which has the function argument written in rather than passed in by a variable.

The reason it seems to stand out is because, usually, you have code to run inside the function, and having a lot of code run on a single line is ugly (although perfectly allowable in Lua).

Part.Touched:connect(function(hit)
    hit.Parent.DoSomething.Value = true
    DoSomething(hit)
    --and so on
end)

This works because Lua ignores almost all whitespace when it is interpreting scripts. Technically, all scripts in Lua can be written on a single line, it's just easier to read when it's spread out.

Answer this question