✓ Accepted answer
Characteristic
The difference between a colon in a function and a period in a function is that the colon has an implicit self parameter while the period doesn't
For example, if it did this:
local tbl = {}
function tbl.Foo ()
print(self)
end
tbl.Foo()
The last line would print nil, but alternatively, if I did:
local tbl = {}
function tbl:Foo ()
print(self)
end
tbl:Foo()
The last line prints table tbl, to test this yourself, you can run this line of code after it to verify:
print(tbl)
Object Oriented Programming
The main use for a colon in the definition of a function is for OOP, or Object Oriented Programming, more specifically gaining access to the object itself without having to send it as an argument.
It's primary use is being an essential part for the inheritance of methods (essentially functions declared with a :)
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 a = Account:new("Joe")
a:deposit(24)
print(a)
print(a.balance)
As you can see in the example, the print self and print a lines both print the same thing, as I am calling the deposit method from account a, and not any other table that contained / inherited that method.
Why this inheritance of methods happens is due to the properties of the __index metamethod, which is a whole other can of worms.
References
oop in lua pil
__index metamethod
Hopefully this helped!
1 comment
This deserves to be te accepted answer. Accepting.