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

What is the difference between variable = function() and function variable() ?

Asked by 6 years ago

Are they the exact same thing, just a user's preference or do they actually do something?

for ex:

function printHello ()
    print ("Hello")
end

Hello = function ()
    print ("What does this do?")
end

printHello()
Hello()

I checked the output. It prints both of them when I call. So does it matter which one I use???

This question is just asked for clarification
0
I tested this in roblox studio and they are both the same i assume. Hwk3r 0 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago

"Are they the exact same thing, just a user's preference or do they actually do something?" No not really at all.

The first method for defining a function always require the function syntax, a title, and parenthesis (which I'm guessing you already know):

function printHello ()
    print ("Hello")
end

The second method allows you to create an ambiguous function that doesn't require you to define it. There are no extra features hat come with ambiguous functions, though they do allow for more compact code in some situations...

workspace.Changed:connect(function()

end) --compact
--instead of...
function a()

end
workspace.Changed:connect(a) --less compact

Creating an ambiguous can be helpful when you want to compact code without having to define another function, though really it's a developer preference that doesn't affect how the code is ran.

The only minor difference between the two is attaching it to a table, like so...

--Would work:

t = {}
function t:add() --Allows you to 

end

--Wouldn't work (would error instead):

t = {}
t:add = function()

end

--So instead you'd have to write it like this:

t = {}
t.add = function()

end

It isn't a major difference, and again, it really comes down to the developers preference. Though to me it does look a bit more organized when your able to insert into the table with a colon :3 (just my opionin).

1
called anonymous functions or lambdas btw. cabbler 1942 — 6y
Ad

Answer this question