There’s a small difference between : notation and . notation.
When you use . notation, that object is just like any other table.
local myTable = {} myTable.number = 1 myTable.addToSelf = function( increment ) myTable.number = myTable.number + increment return myTable.number end return myTable
However, : notation has a special meaning. It’s a shorthand that keeps track of a reference to ‘self’, as Rob said.
local myTable = {} myTable.number = 1 function myTable:addToSelf( increment ) self.number = self.number + increment return self.number end return myTable
But technically, : notation is just a shorthand for doing this
local myTable = {} myTable.number = 1 myTable.addToSelf = function( self, increment ) -- do stuff end return myTable
There is always an implicit self as the first parameter when you use : notation. Lua won’t let you pass a reference to a function using : notation though, it’s specifically used for calling a function. That’s why you get the syntax error. You have to use . notation to pass references, BUT keep in mind the self parameter when you do.
If the function you are passing as a reference doesn’t take any parameters, then you can simply do this
local test = {} function test:f2() print("Hello") end local function p(\_c) \_c() end p(test.f2) -- Output is "Hello"
The reason why your test f2 didn’t work is because technically you are doing this
test.f2 = function(self, n) --self = 3 --n = nil print("f2: ", n) end local function p(\_c) \_c(3) end p(test.f2)
If you absolutely need to use : notation, then you have to wrap the call inside an anonymous function like this
local test = {} function test:f2(n) print("f2: ", n) end local function p(\_c) \_c(3) end p( function(n) test:f2(n) end ) -- Output is "f2: 3"