Difference between : and .?

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!

3 Likes

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
22 Likes

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.

1 Like

So, if I were to do:

function module:ColonFunction()
    self.Hi = true
end

would that work if self is defined as the table the function belonged to, and Hi is a variable, as you said?

self would be module therefore if there was an index named Hi inside module then it’d be set true.

That’s what I thought. And if I used

function module.DottedFunction()
    self.Hi = true
end

this would return an error as self is undefined, right?

Yep, unless you defined self as a parameter.

OK. Thanks a lot!

30characters

1 Like

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)
7 Likes