I don't remember where I saw this so I can't necessarily write the script correctly, but I do remember seeing a colon in one of a script that a friend of mine wrote a while back.
local function functionName:example1() end local function functionName:example2() end
What does this do and how could I use this? Thanks in advanced.
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)
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.
Hopefully this helped!
I'm pretty sure functionName
is a table, and example..x
is the function name.
For example, if you try to run the script below:
local function functionName:ex1() print("2s") end
the colon would be underlined red cause it's not a valid function name, and expects a paranthesis. Same thing with regular functions:
function functionName:ex2() print("1s") end
Except functionName would be nil unless it's a table, like this:
local TestingTable = {} function TestingTable:Example1() return "Example1" end print(TestingTable.Example1)
But for some reason, local functions can't access tables from the server(This only happens to the name)