Methods are unique functions which belong to a particular object. Some common Roblox methods include
A method acts like a function stored within an object, accessible in the same way a function within a table is accessed. However, a special property of methods changes how they are called.
The following two lines of code are equivalent, calling the function
testFunction() with the argument
testObject. Note the usage of dot notation (
.) versus colon notation (
The second (method call) is obviously more concise since there’s no need to retype variable names.
Creating your own methods can help keep your code clean and make tables more dynamic. First, you’ll need a table to apply the method to, for instance:
To add a method to the
testButton table, include a key-value pair where the key is the desired method name and the value is the method function. For example:
Calling a Method
When you call a function as a method, you automatically pass an argument as the table itself, referenced by
self in the example above. This can be proven by printing the value of
testButton.enabled directly and by printing the value of
self.enabled inside the method:
Just like other functions, you can pass arguments to a method function. Note, however, that your additional arguments must be listed after the
self argument of the method, as
self refers to the method’s parent table.