lcgecko
(lcgecko)
April 26, 2020, 2:19am
#1
I have always wrote my modules like this:
module = {}
function module:ARandomFunction()
print(“hello”)
end
return module
But I noticed most people do this:
module = {}
function module.ARandomFunction()
print(“hello”)
end
return module
What’s the difference (If any)?
2 Likes
sjr04
(uep)
April 26, 2020, 2:20am
#2
The difference is
function a:b()
end
is syntax sugar (a nicer way to write something) for
function a.b(self)
end
Which itself is syntax sugar for
a.b = function(self)
end
The call a:b()
is the same as a.b(a)
.
Though please search before posting. I was able to find these:
For example:
local player = game:GetService(“Players”).LocalPlayer
In this line of code after game we use the semi-colon and afterwards we use the dot to refer
to LocalPlayer. What exactly is the difference between a dot and a colon?
I’ve heard some people say that : passes self as an argument, but I don’t understand that.
So, if I had this code here, in a ModuleScript or whatever:
local module = {}
function module.DottedFunction() print("my confusion is here") end
function module:ColonFunction() print("is there a difference between this and dots?") end
return module
would the . or the : make any difference on how they run? Also, can : be used for variables like
module:Hi = false
Please help!
5 Likes
When calling a function with a colon (:
), it implicitly sets self
to the table of the function called. module:Hello()
is also sugar syntax for module.Hello(module)
2 Likes
lcgecko
(lcgecko)
April 26, 2020, 2:24am
#4
I have searched for this topic but was unsuccessful. I’m not sure why I didn’t come across those. Thanks for the example though.
lcgecko
(lcgecko)
April 26, 2020, 2:26am
#5
Also which method is the preferred option?
sjr04
(uep)
April 26, 2020, 2:27am
#6
One is not necessarily better than the other. They have their uses. For instance, if you are making a class and you want to define a method you use :
because a method is a member function so you want to call it on an instance of a class
Otherwise you use a .
if you are not working in an OOP environment
lcgecko
(lcgecko)
April 26, 2020, 2:30am
#7
Ok thanks! Also the first of the two topics you sent is not relevant