What is the difference between module.function and module:function?

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

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:

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

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.

Also which method is the preferred option?

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

Ok thanks! Also the first of the two topics you sent is not relevant