Help with Methods docs

Hello guys, I was reading the docs about the methods and the truth is that I did not understand completely well and I would like to know if someone could better explain the:

  • Custom Methods
  • Calling a Method
  • Additional Arguments

Please, it’s that I’ve been reading it for a long time since the docs and I can’t understand :frowning:

Methods (roblox.com)

A custom method is essentially a function inside of a table with the first parameter being self or the table itself.

Here’s one way to define it:

local tab = {

    methodName = function(self)

    end

    value = 10

}

Here, inside of the method, self.value would be 10 because remember, as said in the article, the method is essentially doing tab.methodName(tab) which we can shorten to tab:methodName().

But the conventional way is:

function tab:methodName() --here you don't need to have self, it's automatically there!

end

Though, you should probably use PascalCase instead of camelCase for methods (as the latter is more associated with deprecated stuff, but it’s fine if you use it).

You can call the method simply like a function, but using : instead. It is exactly like using . and is still considered indexing the table:

tab:methodName() --there
tab.methodName() --this works but doesn't pass the self parameter

(If you know __index, the metamethod is fired when you call a method of a table. Here the index would be methodName.)

Now, you can pass additional arguments when calling the method and they will be passed right after the self parameter if you use this way of defining methods:

local tab = {

    methodName = function(self, param1, ...)

        print('Arg 1 is ' .. param1)
        print(...)

    end

}

--call
tab:methodName("Blah", 2, {}, "anything here") 
-- Arg 1 is Blah
-- 2 table: xxxxxxxx anything here

If you’re defining them more conventionally, then you can simply write the parameters without having self.

I hope this helps!

3 Likes

Wow thank you very much indeed! You have helped me a lot :smiley: :smiley:

1 Like

can i do something like this or what is wrong in my code? :scream:

local tab = {
	{methodName = function(self, param1, ...)
		print('The arg 1 is: ' .. param1)
		print("The ... here → ",...)
	end}
	
	{methodName2 = function(self, param1, ...)
		print('p1 ' .. param1)
		print("p2",...)
	end}
}

--call
tab:methodName2("Method has been called.")