Quick question regarding "self" functionality

Hey, so I typically thought when you create functions/methods on a table object in this manner:

local tab = {}
function tab:Init(y)
    self.x = 4
end

That the ‘self’ parameter is only usable when no arguments are defined. However, upon discovery even if I have a parameter in my function like this for example, the ‘self’ parameter still points to the ‘tab’, or whatever table object the function is a field of.

Just curious as to what the rules are for the self keyword. Thanks!

1 Like

function tab:Init(y) is the same as function tab.Init(self, y); the self parameter is implicit with the : syntax.

4 Likes

So despite how many arguments I define for a function, the self argument would still be usable??

The first argument to the function when calling it with : is the table, which is passed to the first parameter. If the function was defined using : then the first parameter is the hidden self parameter. The number of additional parameters has no effect. Here are some of the differences:

local t = {}
function t:f(...)
	print(...)
end
function t.g(...)
	print(...)
end

t:f(1, 2, 3)    -- > 1 2 3
t.f(t, 1, 2, 3) -- > 1 2 3
t.f(1, 2, 3)    -- > 2 3
t:g(1, 2, 3)    -- > table: 0x1234567 1 2 3
t.g(t, 1, 2, 3) -- > table: 0x1234567 1 2 3
t.g(1, 2, 3)    -- > 1 2 3
2 Likes

I see, thanks!

I guess I must’ve made a different mistake in the code that caused it to bug.