GSmGpE6CwX2y9JjB25B8
We use cookies on this site to enhance your user experience

Aug 29 2019, 9:17 AM PST 2 min

Methods are unique functions which belong to a particular object. Some common Roblox methods include Instance/Destroy|Instance:Destroy(), Instance/Clone|Instance:Clone(), and Instance/FindFirstChild|Instance:FindFirstChild().

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 (:).

testObject.testFunction(testObject)
testObject:testFunction()

The second (method call) is obviously more concise since there’s no need to retype variable names.

Custom Methods

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:

local testButton = {
	enabled = true,
	imageActivated = "rbxgameasset://Images/ImageButtonActivated",
	imageNormal = "rbxgameasset://Images/ImageButtonNormal"
}

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:

local testButton = {
	enabled = true,
	imageActivated = "rbxgameasset://Images/ImageButtonActivated",
	imageNormal = "rbxgameasset://Images/ImageButtonNormal",
	changeEnabled = function(self)
		self.enabled = not self.enabled
	end
}

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:

Additional Arguments

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.

Tags:
  • lua
  • method
  • function