How to Get `Self` from metatable

If you call a function of an object with a colon instead of a period, the object is passed implicitly as the first argument, self. Additionally, if you define the function of an object with a colon instead of a period, self will already be implicitly defined as the first argument.

For example, if we create an object as

local Object = {}
Object.__index = Object

function Object.new()
	return setmetatable({}, Object)
end

local obj = Object.new()

then both of these lines of code are functionally identical:

obj:DoSomething() -- colon operator implicitly passes obj as first argument

obj.DoSomething(obj) -- period does not pass obj as first argument, we must pass it ourselves

and for defining the function, both of these methods will also be functionally identical:

function Object:DoSomething()
	print(self)
end

function Object.DoSomething(self)
	print(self)
end
2 Likes