OOP self keyword

So I am curious about how the self keyword is used with the : operator.

so I have this code

local z = {
    a = 1,
	test = function()
		self.a = 2
	end
}
z:test() // will error

where I get that error (unknown global self)

however if I just were to put in the paramter self into the function like so

local z = {
    a = 1,
	test = function(self)
		self.a = 2
	end
}
z:test()

I am curious to why I have to put that self keyword into the parameter even though I am not passing it, I am using the : operator. if I don’t use the f = function() syntax, and just use the regular function z:test() syntax I don’t need to put self in as a argument.

self is automatically added as an implicit first parameter when you use the “method-like” function syntax. See these examples:

-- These are equivalent.
function z:test(arg1)
end

function z.test(self, arg1)
end

z.test = function(self, arg1)
end

-- So are these.
z:test()
z.test(z)

You’ll probably want to move your function out of the table literal for z and write it function z:test(). Otherwise, you will have to include self as the first parameter like you showed.

7 Likes

Hmm I can see why that would work like that now, thanks for explaining this to me :slight_smile: