The colon is just “syntax sugar” that automatically fills the self variable with the table before the colon.
For example, these are the same:
local oopCar = OOPCar.new()
oopCar:Drive("Forward")
oopCar.Drive(oopCar, "Forward") -- Just another way of calling the same function
So to answer your question, you can do:
local a = {
['men'] = 'kind',
['method'] = function(self) -- Add the self variable here, it gets auto filled by using a ":" instead of a "."
print(self)
print(self.men)
end
}
a:method() -- Now this works
-- You can also do this to run the same function:
a.method(a)
local a = {
['men'] = 'kind'
}
a.method = function(self)
print(self)
print(self.men)
end
a:method() -- This works
-- Run the same function:
a.method(a)
Calling with table.method() doesn’t automatically add the self variable. It just fills in the parameters in the order they’re given. When table:method() is called, the first parameter of the function is automatically filled with self (i.e. table), then the arguments given after that fill the next variables.
When a function is defined as a method (i.e. defined with a colon) it secretly adds the self variable as the first parameter.
local myTable = {
name = "my name"
}
-- All of these add the same function to `myTable`
myTable.method = function(self, a, b, c)
print(self.name .. a .. b .. c)
end
function myTable.method(self, a, b, c)
print(self.name .. a .. b .. c)
end
function myTable:method(a, b, c)
print(self.name .. a .. b .. c)
end
-- All of these call `method` with the same arguments
myTable.method(myTable, " a", " b", " c")
myTable:method(" a", " b", " c")