Is there ever a time when you should use method calls over function calls in your own code? I can't think of any instances that require you to implicitly pass self
because self
isn't available. Any examples or explanations would be helpful.
Yes,specifically with object oriented programming, or OOP.
Object oriented programming , or OOP as it is abbreviated to, is an aspect of many languages that include classes such as java
and c++
The primary use for self
/methods in lua OOP is method inheritance, the being that methods are passed from a parent class to a child class, for example, in roblox, all instances have the properties, functions, and events of the instance class, being the parent class.
Account = {balance = 0} function Account:new (name) local o = {name=name} setmetatable(o, self) self.__index = self return o end function Account:deposit (v) self.balance = self.balance + v print(self) end local acc = Account:new("john") acc:deposit(111) print(acc.balance)
as you can see there, the acc subclass of the parent class Account
inherits all methods and properties of said parent class, and any extra properties and methods you define.
Also, you may notice that when it is printing self
in the deposit method when it was ran on line 16, it prints the acc
table, or class
you can verify this yourself by doing:
print(acc)
the self in this case is always the table the method was executed from.
Now this also means you can make a subclass of a subclass, and then make a subclass of that, so on so forth.
However, if that isn't what is necessitated, the new
function can be declared as a non-method, which is probably the reason roblox uses .new
.
Hopefully this helped you understand the use of
self
better, and if you are any bit confused, just leave a comment
for the in depth explanation of OOP head chapter 16 of the lua pil here