Why do people use “:” when writing functions, and what does it mean?
function functionName:idk()
end
Why do people use “:” when writing functions, and what does it mean?
function functionName:idk()
end
this is for use with tables, in relation to oop, sets the first argument of the function as an implicit reference to itself.
local player = {
hp = 100
}
function player:TakeDamage(damage)
self.hp -= damage
end
--is the same as
function player.TakeDamage(plr, damage)
plr.hp -= damage
end
The colon operator, ( : ), is a special syntax often associated with object-oriented design. It is essentially “syntactic sugar” as you can make equivalent calls using the dot operator, ( . ), as well. The self keyword also ties into this, which you can see in the example below:
--Object-oriented 'Account' design
local Account = {}
Account.__index = Account
function Account.new()
local newAccount= setmetatable({ Balance = 0 }, Account)
return newAccount
end
function Account:Deposit(amount)
self.Balance = self.Balance + amount
end
--Create a new Account
local myAccount = Account.new()
--Using the colon operator
myAccount:Deposit(100)
--Equivalent call using the dot operator
myAccount.Deposit(myAccount, 100)
What does self do though? character limit
You can only use the self keyword if you define the function with the colon operator. Otherwise, you would have to add an additional argument:
function Account:Deposit(amount)
self.Balance = self.Balance + amount
end
--The function above is equivalent to the one below, except think of `x` as `self`
function Account.Deposit(x, amount)
x.Balance = x.Balance + amount
end
Note: Using the second definition of Deposit, even though it is defined with the dot operator, you could still call the function using the colon operator:
local myAccount = Account.new()
myAccount:Deposit(100)
As @arbitiu said, the colon operator is a way of implicitly passing a reference to the object that comes before it.
TL;DR:
function functionName:idk(fizz)
print(fizz)
print(self)
end
is the exact same as
function functionName.idk(self, fizz)
print(fizz)
print(self)
end
and
functionName:idk()
is the same as
functionName.idk(functionName)
You use the colon : when you want to have access to the table/object the function was called from.
For example, Humanoid:MoveTo() needs to know what Humanoid to move, so it needs access to the object MoveTo was called on, so it uses a colon instead of a dot.
Y’know, you can make x in the second function “self”. It’s not a reserved keyword ![]()
Yeah, I’m aware of that. I didn’t make it self because the linter will still pick it up as if it was a keyword… It’s one of those weird things where either approach could lead to some confusing without a lengthy explanation ![]()
I’ve never had any issues with the linter ![]()