How to make an OOP function in the table?

I know something like function testtable:test()end works but im wondering if i can put it inside the table itself. I tried this and didn’t work

local a={
  ['men']='kind',
  method=function()
    print(self)
  end
}
function a:test()
  print(self['men'])
end
a:test()--kind
a:method()--nil

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)

1 question, if you do like table.method it wouldn’t define it automatically would it ?

1 Like

Setting it with table.method is the same:

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.

For example, all of these do the same thing:

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")

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.