A custom method is essentially a function inside of a table with the first parameter being self
or the table itself.
Here’s one way to define it:
local tab = {
methodName = function(self)
end
value = 10
}
Here, inside of the method, self.value
would be 10 because remember, as said in the article, the method is essentially doing tab.methodName(tab)
which we can shorten to tab:methodName()
.
But the conventional way is:
function tab:methodName() --here you don't need to have self, it's automatically there!
end
Though, you should probably use PascalCase instead of camelCase for methods (as the latter is more associated with deprecated stuff, but it’s fine if you use it).
You can call the method simply like a function, but using :
instead. It is exactly like using .
and is still considered indexing the table:
tab:methodName() --there
tab.methodName() --this works but doesn't pass the self parameter
(If you know __index
, the metamethod is fired when you call a method of a table. Here the index
would be methodName
.)
Now, you can pass additional arguments when calling the method and they will be passed right after the self
parameter if you use this way of defining methods:
local tab = {
methodName = function(self, param1, ...)
print('Arg 1 is ' .. param1)
print(...)
end
}
--call
tab:methodName("Blah", 2, {}, "anything here")
-- Arg 1 is Blah
-- 2 table: xxxxxxxx anything here
If you’re defining them more conventionally, then you can simply write the parameters without having self
.
I hope this helps!