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
Colon functions are what’s called syntatical sugar, they’re special pieces of code.
They allow use of the self parameter without defining it, self is what table the function belongs to.
Only functions can make use of this.
If you were to call a colon function as a full stop function then you’d have to provide self yourself as the first argument.
ie.
local t = {
Cheese = "nice"
}
function t:foo()
print(self.Cheese)
end
t:foo() --nice
t.foo(t) --nice
I personally don’t think it makes any difference on the performance, but I might be wrong. I tend to use the period (.) when using variables, and semicolon (:) when I declare functions.
Just to plug: in normal code, what you use changes depending on your preferences or needs often at times. I’ve often seen colon syntax used for OOP; not so much for anything else, except keeping consistency with the API of Roblox objects.
local Superclass = {}
Superclass.__index = Superclass
Superclass.__type = "Data"
local Subclass = setmetatable({}, Superclass)
Subclass.__index = Subclass
function Superclass.new()
local object = setmetatable({}, Superclass)
return object
end
function Subclass.new()
local object = setmetatable({}, Subclass)
return object
end
function Superclass:GetType()
print(self.__type)
end
local TestObject = Subclass.new()
print(TestObject:GetType()) -- Data (inherited from superclass)