Does making a function in a ModuleScript a method do anything different

I have been seeing lots of people making their functions in module scripts methods and I am wondering does doing this enhance the function. Here is an example:

local module = {}

function module:Run()  -- This is the method function because it has a colon in the middle of module and run
	print("This function is running")
end

function module.Run()  -- This is the function without the method
	print("This function is running")
end

return module

From my understanding both of the above functions do the exact same thing so I am assuming making a function a method just improves the readability of the script. I could be totally wrong so I am asking you.

3 Likes

These two functions do exactly the same thing.


You can pass the data into the function without including it into the parameters using :, for example:

function module:Add5()
	return self + 5
end

This looks neat and we don’t need to pass the variable. It’s very handy when doing OOP style coding.

Notice there is a self variable. This is the variable that is automatically passed.

You can learn about Lua OOP here, it’s very handy!


These two things do exactly the same thing, but the second one looks nicer, and we don’t need to pass the data.

beep.boop(beep)
beep:boop()

Edit

The effect of the colon is to add an extra hidden parameter in a method definition and to add an extra argument in a method call.

The colon is only a syntactic facility, although a convenient one; there is nothing really new here. We can define a function with the dot syntax and call it with the colon syntax, or vice-versa, as long as we handle the extra parameter correctly

3 Likes

When you call a function with a colon operator, the first argument becomes self. This is helpful when making classes, since self is the table that the function is being called from. For example:

t = {}
t2 = {}
local function setter(self, index, value) -- just an example function that checks if it's a number before setting
     if typeof(value) == "number" then
          rawset(self, index, value)
     end
end
t.func = setter
t2.func = setter
t:func(1,2) -- notice we use : and don't type the first arg
t2:func(1,5) -- and same function diff table
print(t[1]) --> 2
print(t2[1]) --> 5

This is useful if you use OOP and have classes where each member of a class uses the same functions but have different properties set.

5 Likes